/* 
NAME: fdi.do
USING .dta file(s): 
	authoritarianism_fdi_062015.dta
	habermenaldo_original.dta
	oil.dta
	GWF.dta
	seizure.dta
	tradeconcentration.dta

USING .do file(s): cowcodes.do

DESCRIPTION: This program merges data together, creates variable transformations (including 
	a personalism index), and analyses the relationship between regime type and export
	concentration as well as regime type and sectoral FDI

AUTHOR: Joseph Wright
ORIGIN DATE: 12.04.15
LAST UPDATE: 11.18.17

*/

capture log close
log using AuthoritarianFDI.log, replace

clear all
set more off
set scheme lean2
global dir ="C:\Users\jgw12\Dropbox\Research\Authoritarianism and FDI\ISQ Final Submission\Replication Files"
global m = 10									/* number of imputated data sets, estimates to average */

capture program drop jwmi
program define jwmi
	matrix c = J(1,$m,1)							/* matrix for obtaining columns sums */		
		* Get and store the estimates *
	matrix est = J($m,2,.)							/* place to store estimates */
	forval i = 1/10{
		qui:est restore $imp`i'						/* get estimate */
		qui:nlcom _b[$v],post
		matrix beta =e(b)
		matrix var = e(V)
		matrix est[`i',1]==beta[1,1]
		matrix est[`i',2]==var[1,1]
	}
	matrix colnames est = beta var
	*matrix list est									/* show the estimates from tests for each imputed data set */
		* Estimate of beta is the mean *
	matrix mean_b = (c*est)/$m						/* calculate the mean of b */
	* Between variance, Vb *
	matrix cvb = J($m,1,.)
	forval i = 1/$m {
		matrix x ==est[`i',1]						/* get the x_i's  */
		matrix cvb[`i',1]==(x[1,1]- mean_b[1,1])^2  /* squared deviations from mean */
	}
	matrix  vb = (c*cvb)/($m-1) 					/* sum squares and divide by n-1 */
		* Within variance, Vw *
	matrix vw = mean_b[1,2]
		*  Total variance *
	matrix tv = vw[1,1] + vb[1,1] + (vb[1,1]/$m)
		* Show the MI beta & se *
	matrix beta= mean_b[1,1]
	matrix se = sqrt(tv[1,1]) 
	matrix list beta
	matrix list se
		* Store results for graphing
	replace b = beta[1,1] if count==$count
	replace se = se[1,1] if count==$count
	replace hi =  beta[1,1] + 1.96*se[1,1] if count==$count
	replace lo =  beta[1,1] - 1.96*se[1,1] if count==$count
	replace mhi =  beta[1,1] + 1.65*se[1,1] if count==$count
	replace mlo =  beta[1,1] - 1.65*se[1,1] if count==$count
	replace model = "$imp" if count==$count
	global count=$count -1
end


		************************************
		*** Figure 1: Expropriation Plot ***
		************************************

			cd "$dir"
			use GWF-All-Political-Regimes, clear
			sort cow year
			merge cow year using expropriations
			tab _merge
			 * expropriations in small countries not in GWF and prior to GWF independence *
			list cow expropriations_country year if _merge==2 & year>1946, clean
			drop if _merge==2
			drop _merge
			* drop countries not coded as democracy or autocracy *
			drop if gwf_duration==. | gwf_nonautocracy == "foreign-occupied" | gwf_non=="warlord/foreign-occupied"

			*** by dictatorship/democracy ***
			egen x_yrexp = sum(allexp) if gwf_non=="NA", by(year)
			egen y_yrexp = sum(allexp) if gwf_non~="NA", by(year)
			egen dict_yr = max(x_), by(year)
			egen dem_yr = max(y_), by(year)
			egen tag  = tag(year)  
			drop if year<1960 | year>2006
			twoway (bar dict_yr year if tag==1,color(gs12) ylab(,glcolor(gs14)) xlab(1960 (10) 2000) /*
			*/ xtitle(Year, height(6)) ytitle(Number of expropriations))  /*
			*/ (line dem_yr year if tag==1, legend(lab(1 "Dictatorship") lab(2 "Democracy") /*
			*/ col(1) pos(3) ring(0)) scheme(lean2) title(By regime) saving(h1,replace))
			drop x_ y_ dict dem tag

			*** by primary/non-primary ***
			egen x_yrexp = sum(pexp), by(year)
			egen y_yrexp = sum(npexp), by(year)
			egen p_yr = max(x_), by(year)
			egen np_yr = max(y_), by(year)
			egen tag  = tag(year)  
			drop if year<1960 | year>2006
			twoway (bar p_yr year if tag==1,color(gs12) ylab(,glcolor(gs14)) xlab(1960 (10) 2000) /*
			*/ xtitle(Year, height(6)) ytitle(Number of expropriations))  /*
			*/ (line np_yr year if tag==1, legend(lab(1 "Primary sector") lab(2 "Other sectors") /*
			*/ col(1) pos(3) ring(0)) scheme(lean2) title(By sector) saving(h2,replace))
			drop x_ y_ p_ np_ tag

			graph combine h1.gph h2.gph, col(2) xsize(3) ysize(1.4) scheme(lean2) b1()
			graph export "$dir\golden\Expropriations.pdf", as(pdf) replace
			graph export "$dir\golden\ISQ-Figure-1.png", as(png) replace
			erase h1.gph
			erase h2.gph

			*** List expropriations between 1980 and 1998, inclusive
			list gwf_case  year sector gwf_personal gwf_mil gwf_party if pexp==1 & year>1979 & year<1999, clean noobs		
			/*							  SECTOR 	PERSONAL	MILITARY	PARTY
				Honduras 81-NA   1983      AGR          0          0          0  
			 El Salvador 48-82   1980      AGR          0          0          1  
			   Nicaragua 79-90   1980      AGR          0          0          1  
			   Nicaragua 79-90   1982      AGR          0          0          1  
					Peru 80-92   1985      PET          0          0          0  
			 Congo/Zaire 97-NA   1998      MIN          1          0          0  
				  Zambia 67-91   1980      PET          0          0          1  
				 Lesotho 86-93   1992      MIN          0          1          0  
			Turkmenistan 91-NA   1996      PET          0          0          1  
			  Kazakhstan 91-NA   1992      PET          1          0          0  
				Pakistan 77-88   1983      AGR          0          1          0  
			   Sri Lanka 78-94   1981      AGR          0          0          1   */

	****************************
	*** Merge and clean data ***
	****************************
	cd "$dir"
	set scheme s1mono //lean1
	global color1="gs1"
	global color2="gs8"
	global color3="gs12"
	
	** Oil reserve data **
	use haber-menaldo, clear
	drop if year<1946
	recode cow (679=678) (818=816)
	tsset cow year
	gen oil = ln(1+l.total_oil_income_pc)
	gen l5reserves= ln(1+((l5.reserves_billions*1000000000)/l5.population))
	gen l1reserves= ln(1+((l1.reserves_billions*1000000000)/l1.population))
	forval i = 6/10 {
		replace l5reserves = ln(1+((l`i'.reserves_billions*1000000000)/l`i'.population)) if l5res==.
	}
	bysort cow: egen minyr  = min(year) if l5reserves~=.
	gen first = l5reserves if minyr==year
	bysort cow: egen firstreserves = max(first)
	gen minyr80 = minyr
	replace minyr80 = 1980 if minyr80<1980
	egen meanfirst = mean(l5res) if year<=minyr80, by(cow)
	egen meanreserves =max(meanfirst), by(cow)  /* pre-1980 -- or first year -- mean reserves */
	drop first minyr* meanfirst
	sum year first*
	sort cow year 
	save hm_merge, replace
	
	** FDI data **
	use authoritarianism-fdi, clear
	rename ccode cowcode 
	drop if cow==.
	sort cow year
	joinby cow year using hm_merge,unmatched(both)
	*drop if year<1980|year>2008
	tab _merge 
	drop if _merge==2
	rename _merge merge2
	erase hm_merge.dta
	egen x = max(meanres), by(cow)
	replace meanres = x if meanres==.
	drop x

	**  Trade concentration data **
	joinby country year using trade-concentration.dta,unmatched(both)
	drop if _merge==2
	drop _merge
	sort cow year
	save temp, replace
	
	*** Expropriation data ***
	merge cow year using expropriations
	tab _merge if year>=1980
	sort cow year
	recode allexp pexp npexp (.=0)
	local var = "allexp pexp npexp"
	foreach v of local var {
		gen original_`v'=`v'
		tsset cow year
		egen x_`v' = filter(`v'), coef(1 0.5 0.25 0.125 0.0625 0.03125 0.015625 0.0078125) lags(1/8) 
		replace `v' = x_`v'  if x_`v'~=.
		drop x_`v'
		tsset cow year
		egen x_`v' = filter(`v'), coef(1 0.5 0.25 0.125 0.0625 0.03125) lags(1/6) 
		gen `v'6 = x_`v'  if x_`v'~=.
		drop x_`v'
		tsset cow year
		egen x_`v' = filter(`v'), coef(1 0.5 0.25 0.125 0.0625 0.03125 .015625 0.0078125 0.003906 .001953) lags(1/10) 
		gen `v'10 = x_`v'  if x_`v'~=.
		drop x_`v'
	}
	*drop if year<1980
	sort year
	drop _merge
	save temp, replace
	
	*** Merge oil price data ***
	use ross-oil, clear
	egen tag = tag(year)
	keep if tag==1
	keep year oil_price*
	sort year
	merge year using temp
	tsset cow year
	gen oilpc = ln(1+l.oil_gas_valuePOP_2000)
	gen oil5pc = ln(1+l5.oil_gas_valuePOP_2000)
	sort cow year
	drop _merge
	tsset cow year
	save temp, replace

	*** POLCON ***
	import excel polcon,  firstrow clear	
	keep if year>1959
	keep ccode year *_country polcon* j f
	rename ccode cowcode
	gen polcon = polconv
	replace polcon = polconiii if polcon==.
	recode cowcode (678=679) (529=530)  (818=816)
	sort cowcode year
	tsset cowcode year
	gen lpolcon = l.polcon
	sort cow year
	merge cow year using temp
	drop _merge
	sort cow year
	save temp,replace

	*** Log transformations for explanatory variables ***
	use temp,clear
	gen lgdpcap=log(cgdpcap)
	gen lgdp=log(cgdp)
	gen lpop=log(pop)
	gen lopenness=log(1+openness)
	hist lopen if gwf_pers~=., bin(50) 
	recode fdi_transition (.=0) if year<1989
	gen ldevelopingfdi=log(fdi_developing+fdi_transition)
	tsset cow year
	gen grow = l.growth
	
	*** Real FDI (PPP adjusted)
	gen rpfdi=rgdpo*1000000/GDP*ISICPrimary
	gen rsfdi=rgdpo*1000000/GDP*ISICSecondary
	gen rtfdi=rgdpo*1000000/GDP*ISICTertiary
	
	*** FDI, share of GDP ***
	gen Primaryfdigdp = ISICPrimary/(GDP/1000000)
	gen Secondaryfdigdp = ISICSecondary/(GDP/1000000)
	gen Tertiaryfdigdp = ISICTertiary/(GDP/1000000)


	*** Log transformations for sectoral FDI data from Real FDI as a share of GDP ***
	local var = "Primary Secondary Tertiary"
	foreach v of local var {
		gen log_`v'fdigdp = ln(1+abs(100*`v'fdigdp))
		replace log_`v'fdigdp = -1*log_`v'fdigdp if ISIC`v'<0
		hist log_`v'fdigdp if gwf_pers~=., bin(50)
	}
	pwcorr  log_Primaryfdigdp log_Secondaryfdigdp log_Tertiaryfdigdp, sig
	
	*** Cube transformations for sectoral FDI data from Real FDI as a share of GDP ***
	local var = "Primary Secondary Tertiary"
	foreach v of local var {
		gen cub_`v'fdigdp = (abs(`v'fdigdp))^(1/3)
		replace cub_`v'fdigdp = -1*cub_`v'fdigdp if ISIC`v'<0
		hist cub_`v'fdigdp if gwf_pers~=., bin(50)
	}
	pwcorr  cub_Primaryfdigdp cub_Secondaryfdigdp cub_Tertiaryfdigdp, sig

	*** Gen region dummies ***
	gen meast = cow>=600 & cow<700
	gen americas = cow<200
	gen ssa = cow>=400 & cow<600
	gen asia = cow>=700 & cow<800
	gen easia = cow>=800

	*** Gen civil war variable ***
	gen civilwar=incidencev413
	replace civilwar=0 if maxintyearv413<2
	keep if gwf_country~=""
	
	*** Merge personalism data ***
	sort cow year
	merge cow year using GWF
	tab _merge
	tsset cow year

	*** Create personalism index using Sample 2 observations ***
	gen allregime = 1 if gwf_non=="democracy" | gwf_non=="provisional"
	replace allregime = 2 if gwf_mil==1
	replace allregime = 3 if gwf_monarchy==1
	replace allregime = 4 if gwf_party==1
	replace allregime = 5 if gwf_personal==1
	sort gwf_leaderid year
	gen newparty = (partyhistory_post & support==1 & gwf_leaderid == gwf_leaderid[_n-1]) | (partyhistory_priordem & support==1) if support~=.
	recode newparty officepers partyhistory_post partyhistory_priordem leaderrel ldr_exp* (.=0) if allregime~=. 	/* set democracies equal to zero on personalism scale */ 
	alpha officepers newparty ldr_exp_pers_rel leaderrel, gen(pers) item     /* create index using the larger sample */
	hist pers, bin(50)
	sum  pers gwf_personal if log_Primaryfdigdp~=.
	gen gtime = ln(gwf_duration)
	
	*** All FDI ***
	gen allfdi  =  (abs(fdigdp_unctad))^(1/3) if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & allregime~=. & year>=1980
	replace allfdi = -1*allfdi if fdigdp_unctad<0 
	egen rawpre80fdi  =sum(fdigdp_unctad) if year<1980, by(cowcode)
	gen pre80fdi80 =  (abs(rawpre80fdi))^(1/3) if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & allregime~=.
	replace  pre80fdi80 = pre80fdi80*-1 if rawpre80fdi<0
	egen pre80fdi= max(pre80fdi80),by(cow)
	drop rawpre80fdi pre80fdi80
	
	* keep only the GWF autocracy and democracy data *
	drop if allregime==.
	drop if year<1979 /*| year>2010*/

	*** Construct instrument ***
	******************************************************************************
	** Note: the instrument for personalist regime is a binary variable for		**
	**		how the first regime leader seized power: election or uprising,     **
	** 		the instrument is constructed from pre-seizure information			**
	**		that correlates with personalist behavior once in power.			**
	******************************************************************************
	recode seizure* (.=0)   /* coded as zero for all democracies */
	gen inst =   (seizure_uprising==1 | (seizure_election==1 & partyhistory_priordem==0))
	drop _merge
	sort cow year
	keep if oecd1==0  /* only non-OECD countries, except Mexico and S. Korea */
	save temp, replace
	
	*** Footnote: average regime duration by type ***
	use temp,clear
	sum year
	egen tag = tag(gwf_casename)
	egen max = max(gwf_duration),by(gwf_casename)
	table allregime if tag==1, c(n year mean max median max)
	
**************************************************************************************************************
	****************
	*** Analysis ***
	****************
	
	**************************
	*** Sectoral FDI tests ***
	**************************
	use temp,clear
	global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
	
	*******************
	* Sample features *
	*******************
	* Note sample sizes *
	hist allfdi if gwf_pers~=., bin(50)
	xtset cow year
	xtregar allfdi gwf_personal $cvarlist  /* 109 countries */
	egen count = count(year) if e(sample)==1,by(cow)
	xtregar allfdi gwf_personal $cvarlist if count>1  /* 108 countries, drop Afghanistan which only have 1 year in estimating sample */
	gen s1=e(sample)==1
	xtregar cub_Primaryfdigdp gwf_personal  $cvarlist  /* 61 countries */
	gen s2 = e(sample)==1
	egen maxs2 = max(s2) if s1==1,by(cow)
	egen tag = tag(cow) if s1==1
	
	* 61 countries in sample, missingness over time *
	gen decade  =year>=1980 & year<1990
	replace decade =2 if year>=1990 & year<2000
	replace decade=3 if year>=2000
	table decade if maxs==1, c(mean s2 mean allfdi mean cub_Prim mean oilpc)
	
	* Cross-section differences between two groups of countries *
	gen m= .
	gen n = _n
	local var = "gwf_pers fdigdp_unctad lpop lgdpcap oilpc meanres"
	local i = 1
	foreach v of local var {
		egen m_`v'  =mean(`v') if s1==1,by(cow)
		egen s_`v' = std(m_`v') if tag==1
		ttest m_`v' if tag==1,by(maxs2) unequal
	}
	egen s_maxs2 =std(maxs) if tag==1
	
	******************
	*** Figure F-3 ***
	******************
 	* Controlling for other things, group is not correlated with total FDI or personalist regime in the cross-section *
	replace m_fdi  = ln(1+m_fdi)
	reg m_fdi s_maxs2  s_lpop s_lgdpcap s_oil if tag==1 ,
	est store f1
	reg m_fdi s_maxs2  s_lpop s_lgdpcap s_mean if tag==1 ,
	est store f2
	glm m_gwf s_maxs2  s_lpop s_lgdpcap s_oil if tag==1 ,fam(binomial) link(logit)
	est store p1
	glm m_gwf s_maxs2  s_lpop s_lgdpcap s_mean if tag==1 ,fam(binomial) link(logit)
	est store p2
	label var s_lpop "Population"
	label var s_lgdpcap "GDPpc"
	label var s_oil "Oil rents"
	label var s_mean `" "Oil    " "reserves"  "1980   " "' 
	label var s_maxs2 `" "Included"  "countries" "' 
	coefplot (f1, msymbol(T) mfcolor($color1) mcolor($color1) msize(medlarge) ciopts(lcol($color1 $color1))) /*
	*/ (f2, msymbol(O) mcolor($color3) mfcolor($color3) msize(medlarge) ciopts(lcol($color3 $color3))), /*
	*/ title("Total FDI")  scheme(lean2) drop(_cons) order(maxs s_lgdpcap s_lpop s_oil s_mean) xlab(-.2 (.1) .2) xline(0, lpattern(dash)) /*
	*/ grid(glcolor(gs15)) mfcolor(white) ysize(2) xsize(3) saving(h1.gph,replace) /*
	*/ legend(off) level(95 90)   xtitle("  Coefficient estimate", height(6)) 
	coefplot (p1, msymbol(T) mcolor($color1) mfcolor($color1) msize(medlarge) ciopts(lcol($color1 $color1))) /*
	*/ (p2, msymbol(O) mcolor($color3) mfcolor($color3)  msize(medlarge) ciopts(lcol($color3 $color3))), /*
	*/ title("Personalist regime")  scheme(lean2) drop(_cons) order(maxs s_lgdpcap s_lpop s_oil s_mean) xlab(-2(1) 1.5) xline(0, lpattern(dash)) /*
	*/ grid(glcolor(gs15)) mfcolor(white) ysize(2) xsize(3) saving(h2.gph, replace) /*
	*/ legend(off)    level(95 90)  xtitle("  Coefficient estimate", height(6)) 
	graph combine h1.gph h2.gph,col(2) ysize(2) xsize(4) scheme(lean2)
	graph export "$dir\golden\sample-conditional-means.pdf", as(pdf) replace

	******************
	*** Figure F-2 ***
	******************
	* Time varying estimate of personalist regime on total FDI is similar is each group of countries *
	gen l2openness = lopenness*4
	gen gr2 = grow/8
	global cvarlist="allexp gtime lgdpcap lpop l2openness gr2 incidencev413 meanres ldevelopingfdi asia america easia ssa"
	xi:xtregar allfdi gwf_personal  $cvarlist if s1==1
	xi:xtregar allfdi gwf_personal  $cvarlist if maxs==1
	est store f1
	xi:xtregar allfdi gwf_personal  $cvarlist if maxs==0
	est store f2
	label var lgdpcap  "GDP per cap."
	label var lpop  "Population"
	label var allexp "Expropriations"
	label var l2openness  "Trade openness"
	label var lopenness  "Trade openness"
	label var gr2 "Growth"
	label var growth "Growth"
	label var incidencev413 "Civil conflict"
	label var meanres  "Oil reserves"
	label var ldevelopingfdi "Total dev. FDI"
	label var gwf_personal `" "Personalist"  "regime" "'
	label var meanreserves   `" "Oil"  "reserves" "'
	coefplot (f1, msymbol(T) mfcolor($color1) mcolor($color1) msize(medlarge) ciopts(lcol($color1 $color1))) /*
	*/ (f2, msymbol(S) mcolor($color2) mfcolor($color2) msize(medlarge) ciopts(lcol($color2 $color2))), /*
	*/ title("Total FDI")  scheme(lean2) drop(_cons gtime asia easia ssa americas) order(gwf_pers) xlab(-.2 (.1) .2) xline(0, lpattern(dash)) /*
	*/ grid(glcolor(gs15)) ylab(,labsize(small)) mfcolor(white) level(95 90) ysize(4) xsize(3) saving(h1.gph,replace) /*
	*/ legend(lab(3 "Included countries") lab(6 "Excluded countries") pos(6) col(2) ring(1))    xtitle("  Coefficient estimate", height(6))
	graph export "$dir\golden\sample-estimates.pdf", as(pdf) replace
	
	****************
	*** Figure 3 ***
	****************
	* Time trend in total FDI is similar in both groups of countries * 
	global bw = 1
	twoway   (lpolyci fdigdp_unctad year if maxs==0 & gwf_pers==0, lcolor(gs13) ciplot(rarea) bw($bw) saving(h1,replace) ///
	legend(lab(4 "Included countries") lab(2 "Excluded countries") order(2 4) pos(6) col(2) ring(1)) ///
	scheme(lean2) yscale(range(-1 9))ylab(,glcolor(gs16)) xtitle(Year)) ( lpolyci fdigdp_unctad year if maxs==1 & gwf_pers==0, ///
	ciplot(rline) bw($bw) ylab(0(4)12,glcolor(gs16)) ytitle("Total FDI, all sectors") xtitle(Year) title(Non-personalist,pos(12) ring(0))  )
	twoway   (lpolyci fdigdp_unctad year if maxs==0 & gwf_pers==1, lcolor(gs13) ciplot(rarea)bw($bw)  saving(h2,replace)  ///
	legend(lab(4 "Included countries") lab(2 "Excluded countries") order(2 4) pos(6) col(2) ring(1)) ///
	scheme(lean2) ylab(,glcolor(gs16)) xtitle(Year))  (lpolyci fdigdp_unctad year if maxs==1 & gwf_pers==1, ///
	ciplot(rline)  bw($bw) yscale(range(-1 9))  ylab(0(4)12,glcolor(gs16)) ytitle("Total FDI, all sectors") xtitle(Year) ///
	title(Personalist,pos(12) ring(0)))  
	gr combine h1.gph h2.gph, xsize(8) title(Total FDI time trend)
	erase h1.gph 
	erase h2.gph
	graph export "$dir\golden\sample-time-trend.pdf", as(pdf) replace
 	graph export "$dir\golden\ISQ-Figure-3.png", as(png) replace

	******************
	*** Figure 2.1 ***
	******************
	cibar allfdi if maxs==1, over1(allregime) graphopts(saving(s1, replace) title(Included countries) scheme(lean2) /*
	*/ ytitle(FDI (%GDP)) xlab(1.45 "Democracy" 2.85 "Military" 4.35 "Monarchy" 5.8 "Party" /*
	*/ 7.25 "Personal") ylabel(0 (.5) 1.5,glcolor(gs15)) legend(off)) barcolor(gs15 gs14 gs13 gs12 gs11) bargap(45)
	cibar allfdi if maxs==0, over1(allregime) graphopts(saving(s2, replace) title(Excluded countries) scheme(lean2) /*
	*/ ytitle(FDI (%GDP)) xlab(1.45 "Democracy" 2.85 "Military" 4.35 "Monarchy" 5.8 "Party" /*
	*/ 7.25 "Personal") ylabel(0 (.5) 1.5,glcolor(gs15)) legend(off)) barcolor(gs15 gs14 gs13 gs12 gs11) bargap(45)
	gr combine s1.gph s2.gph, xsize(4.5) ysize(2) title("Total FDI, all sectors", pos(6))
	graph export "$dir\golden\sample-allfdi-means.pdf", as(pdf) replace
	graph export "$dir\golden\ISQ-Figure-2.1.png", as(png) replace

	******************
	*** Figure 2.2 ***
	******************
	cibar oilpc if maxs==1, level(90) over1(allregime) graphopts(saving(s1, replace) title(Included countries) scheme(lean2) /*
	*/ ytitle("Mean oil rents pc (log)") xlab(1.45 "Democracy" 2.85 "Military" 4.35 "Monarchy" 5.8 "Party" /*
	*/ 7.25 "Personal") yscale(range(0 5.2)) ylabel(0 (1) 5,glcolor(gs15)) legend(off)) barcolor(gs15 gs14 gs13 gs12 gs11) bargap(45)
	cibar oilpc if maxs==0, level(90) over1(allregime) graphopts(saving(s2, replace) title(Excluded countries) scheme(lean2) /*
	*/ ytitle("Mean oil rents pc (log)") yscale(range(0 5.2))  xlab(1.45 "Democracy" 2.85 "Military" 4.35 "Monarchy" 5.8 "Party" /*
	*/ 7.25 "Personal") ylabel(0 (1) 5,glcolor(gs15)) legend(off)) barcolor(gs15 gs14 gs13 gs12 gs11) bargap(45)
	gr combine s1.gph s2.gph, xsize(4.5) ysize(2) title("Oil rents", pos(6))
	graph export "$dir\golden\sample-oil-means.pdf", as(pdf) replace
	graph export "$dir\golden\ISQ-Figure-2.2.png", as(png) replace

	******************
	*** Figure 2.3 ***
	******************
	cibar lgdpcap if maxs==1, level(90) over1(allregime) graphopts(saving(s1, replace) title(Included countries) scheme(lean2) /*
	*/ ytitle("GDP pc (log)") xlab(1.45 "Democracy" 2.85 "Military" 4.35 "Monarchy" 5.8 "Party" /*
	*/ 7.25 "Personal") yscale(range(0 5.2)) ylabel(0 (2) 8,glcolor(gs15)) legend(off)) barcolor(gs15 gs14 gs13 gs12 gs11) bargap(45)
	cibar lgdpcap if maxs==0, level(90) over1(allregime) graphopts(saving(s2, replace) title(Excluded countries) scheme(lean2) /*
	*/ ytitle("GDP pc (log)") yscale(range(0 5.2))  xlab(1.45 "Democracy" 2.85 "Military" 4.35 "Monarchy" 5.8 "Party" /*
	*/ 7.25 "Personal") ylabel(0 (2) 8,glcolor(gs15)) legend(off)) barcolor(gs15 gs14 gs13 gs12 gs11) bargap(45)
	gr combine s1.gph s2.gph, xsize(4.5) ysize(2) title("GDP per capita", pos(6))
	graph export "$dir\golden\sample-gdp-means.pdf", as(pdf) replace
	graph export "$dir\golden\ISQ-Figure-2.3.png", as(png) replace

	********************
	* Imputed data set *
	********************
		******************
		*** Figure F-1 ***
		******************
	 set more off
	 global m = 10									/* number of imputated data sets, estimates to average */

	 forval i = 1/10 {
		import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
		qui:sort cow year
		qui:merge cow  year using "$dir\temp.dta"
		tab _merge
		global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
		qui:tsset cow year
		qui:xtregar cub_Primaryfdigdp gwf_personal $cvarlist, re   /* No imputed data */
		gen s2=e(sample)
		qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist, re 
		est store impRE`i' 
		gen s1=e(sample)
		tab s1 s2
		twoway (hist cub_primaryfdigdp if s1==1 & s2==0,bin(60) bcol(gs14) title(Imputed data `i',size(medsmall) height(6))) ///
		(kdensity cub_Primaryfdigdp if s2==1,bw(.01) lcol(gs1) legend(lab(1 "Imputed") lab(2 "Observed") ///
		col(1) ring(0) size(vsmall) pos(2)) xtitle("Primary FDI, %GDP",height(4)size(medsmall)) ///
		xlab(-.4 (.4) .8) ytitle(Density,size(medsmall)) scheme(lean2) ylab(,glcolor(gs16)) saving(h`i',replace))
	}
	gr combine h1.gph h2.gph h3.gph h4.gph h5.gph h6.gph h7.gph h8.gph h9.gph h10.gph,col(2) xsize(3) ysize(6)
	graph export "$dir\golden\imputed-data.pdf", as(pdf) replace


	/* 
	Rubin (1987)
	MI estimate of beta is the mean of the betas from each estimated beta 
	MI estimate of variance is: Vb + Vw + Vb/m
		where Vb is the between variance, Vw is the mean variance, and Vb/m is the sampling variance:
			Vb is the sum of the squared deviations from the mean of the estimated betas
			Vw is the mean of the sampling variances (SE) from each of the 10 imputed datasets
	*/ 
	
	****************
	* Main figures *   
	****************
	cd "$dir"
	use temp,clear
	recode seizure_* (.=0)
	global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
	tsset cow year		 
	set more off
	
	
	capture program drop jwmi
	program define jwmi
		matrix c = J(1,$m,1)							/* matrix for obtaining columns sums */		
			* Get and store the estimates *
		matrix est = J($m,2,.)							/* place to store estimates */
		forval i = 1/10{
			qui:est restore $imp`i'						/* get estimate */
			qui:nlcom _b[$v],post
			matrix beta =e(b)
			matrix var = e(V)
			matrix est[`i',1]==beta[1,1]
			matrix est[`i',2]==var[1,1]
		}
		matrix colnames est = beta var
		*matrix list est									/* show the estimates from tests for each imputed data set */
			* Estimate of beta is the mean *
		matrix mean_b = (c*est)/$m						/* calculate the mean of b */
		* Between variance, Vb *
		matrix cvb = J($m,1,.)
		forval i = 1/$m {
			matrix x ==est[`i',1]						/* get the x_i's  */
			matrix cvb[`i',1]==(x[1,1]- mean_b[1,1])^2  /* squared deviations from mean */
		}
		matrix  vb = (c*cvb)/($m-1) 					/* sum squares and divide by n-1 */
			* Within variance, Vw *
		matrix vw = mean_b[1,2]
			*  Total variance *
		matrix tv = vw[1,1] + vb[1,1] + (vb[1,1]/$m)
			* Show the MI beta & se *
		matrix beta= mean_b[1,1]
		matrix se = sqrt(tv[1,1]) 
		matrix list beta
		matrix list se
			* Store results for graphing
		replace b = beta[1,1] if count==$count
		replace se = se[1,1] if count==$count
		replace hi =  beta[1,1] + 1.96*se[1,1] if count==$count
		replace lo =  beta[1,1] - 1.96*se[1,1] if count==$count
		replace mhi =  beta[1,1] + 1.65*se[1,1] if count==$count
		replace mlo =  beta[1,1] - 1.65*se[1,1] if count==$count
		replace model = "$imp" if count==$count
		global count=$count -1
	end

		
		***************************************
		* Figure 4: Primary FDI, RE, AR(1)  *
		***************************************
			forval i = 1(1)$m {
				import delimited using "$dir\imputed-fdi\\primary`i'.csv",clear
				qui:sort cow year
				qui:merge cow  year using "$dir\temp.dta"
				tab _merge
				global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
				qui:tsset cow year
				xtserial cub_primaryfdigdp gwf_personal $cvarlist
				qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist, re 
				est store primaryAR1RE`i'
			}
			
				gen hi =.
				gen lo =.
				gen mhi  =.
				gen mlo =.
				gen b =.
				gen se = .
				gen count =_n
				gen model = ""
				gen variable = ""			
				global count=10									/* number of specifications to test */
				global ac = $count
				global imp ="primaryAR1RE"
				local var = "gwf_pers allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi"
				foreach cvar of local var {
						global v = "`cvar'"						/* name of variable of interest to plot */
						qui:replace variable = "$v" if count==$count
						jwmi 
				}
				gen e=round(b,.001)
				gen s=round(se,.001)
				browse variable e s hi lo
				
				twoway (scatter count b if count<=10,ylab(1(1)$ac,glcolor(gs16)) mlab(e) mlabpos(12) xlab(-.05(.05).1) ///
				mcolor(gs6) msymbol(plus) yscale(range(0.75 10.25))  xtitle(Coefficient estimate) xline(0,lpat(dash))) ///
				(rspike hi lo count if count<=10, horizontal ytitle("") title(Personalist and Primary FDI,size(medium)) ///
				ylab(1 "Total Developing FDI" 2 "Oil reserves per cap. (log)" 3 "Civil conflict"  ///
				4 "Annual GDP Growth" 5 "Trade (log)" 6 "Population (log)" 7 "GDP per cap. (log)" ///
				8 "Regime duration" 9 "Expropriations" 10 "{bf:Personalist}")  lcolor(gs6) lwidth(medthin) ///
				legend(off) scheme(lean2)) (rspike mhi mlo count if count<=10, lwidth(thick) lcolor(gs6) horizontal)
				graph export "$dir\golden\Main-Model.pdf", as(pdf) replace
				graph export "$dir\golden\ISQ-Figure-4.png", as(png) replace
				
		
				********************************************************************************
				*** Check bounds of omitted variable bias in OLS with FE treated as controls ***
				*** Oster, Emily. "Unobservable selection and coefficient stability: Theory  ***
				*** and evidence." Journal of Business & Economic Statistics (2014).         ***
				********************************************************************************
				set scheme lean2
				global m = 10									/* number of imputated data sets, estimates to average */
				matrix psa = J(10,4,.) 
				forval i = 1(1)$m {
					import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
					qui:sort cow year
					qui:merge cow  year using "$dir\temp.dta"
					global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 ldeveloping meanres asia america easia ssa"
					qui:tsset cow year
					qui:reg cub_primaryfdigdp i.cow gwf_pers  $cvarlist, 
					qui:nlcom _b[gwf_pers],post
					matrix beta =e(b)
					matrix psa[`i',1]=beta[1,1]
					matrix psa[`i',2]=e(N)
					qui:reg cub_primaryfdigdp gwf_pers $cvarlist, 
					qui:psacalc beta gwf_pers,delta(.5) rmax(1)
					matrix psa[`i',3]=r(beta)
					matrix psa[`i',4]=r(altsol1)
				}
				matrix list psa  	/* weird Large value in psa[4,3] */
				mat psa[4,3]=0  	/* conservatively assume true value is 0 */
				matrix list psa
				mata : st_matrix("B", (colsum(st_matrix("psa"))/10))
				matrix list B  		/* if there is bias in the OLS estimate, it is downwards */
 
	************
	* Figure 7 *  Compare FDI sectors   & Oil vs. No oil
	************	
			* Different types of FDI *
				* Secondary *
			forval i = 1(1)$m {
				import delimited using "$dir\imputed-fdi\secondary`i'.csv",clear
				qui:sort cow year
				qui:merge cow  year using "$dir\temp.dta"
				tab _merge
				global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
				qui:tsset cow year
				xtserial cub_secondaryfdigdp gwf_personal $cvarlist
				qui:xtregar cub_Secondaryfdigdp gwf_personal $cvarlist, re   /* No imputed data */
				gen s2=e(sample)==1
				qui:xtregar cub_secondaryfdigdp gwf_personal $cvarlist, re 
				gen s1=e(sample)==1
				tab s1 s2
				qui:xtregar cub_secondaryfdigdp gwf_personal $cvarlist, re 
				est store secondAR1RE`i'
			}
				* Tertiary *
			forval i = 1(1)$m {
				import delimited using "$dir\imputed-fdi\tertiary`i'.csv",clear
				qui:sort cow year
				qui:merge cow  year using "$dir\temp.dta"
				tab _merge
				global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
				qui:tsset cow year
				xtserial cub_tertiaryfdigdp gwf_personal $cvarlist
				qui:xtregar cub_Tertiaryfdigdp gwf_personal $cvarlist, re   /* No imputed data */
				gen s2=e(sample)==1
				qui:xtregar cub_tertiaryfdigdp gwf_personal $cvarlist, re 
				gen s1=e(sample)==1
				tab s1 s2
				qui:xtregar cub_tertiaryfdigdp gwf_personal $cvarlist, re 
				est store tertAR1RE`i'
			}
					
					gen hi =.
					gen lo =.
					gen mhi  =.
					gen mlo =.
					gen b =.
					gen se =.
					gen count =_n
					gen model = ""
					global count=3									/* number of specifications to test */
					global ac = $count
					global v = "gwf_personal"						/* name of variable of interest to plot */
					global imp ="primaryAR1RE"
					jwmi
					global imp ="secondAR1RE"
					jwmi
					global imp ="tertAR1RE"
					jwmi 
					
					gen e=round(b,.001)
					browse model e hi mhi mlo lo
					
					twoway (scatter count b if count <=$ac,ylab(1(1)$ac,glcolor(gs16)) mlab(e) ///
					mlabpos(12) xlab(-0.05(.05).1) mcolor(gs6) msymbol(plus) yscale(range(0.75 3.25)) ///
					xtitle(Personalist estimate) xline(0,lpat(dash))) (rspike hi lo count if count<=$ac, horizontal ytitle("") ///
					title("Personalism and sectoral FDI",size(medium)) ylab(1 "Tertiary" 2 "Secondary" 3 "Primary") ///
					lcolor(gs6) lwidth(medthin) legend(off) scheme(lean2) saving(h1.gph,replace)) ///
					(rspike mhi mlo count if count<=$ac, lwidth(thick) lcolor(gs6) horizontal) 
			 
	
				twoway (line ISICPrimary year if gwf_country=="Tunisia" & ISICTertiary~=., /*
				*/ text(2475 2006 "Tunisie Telecom" "2006 privatization", place(sw)) /*
				*/ color(red) xtitle(Year) ytitle("Constant dollars (millions)", height(6))scheme(lean2) xlab(1990 (5) 2005) /*
				*/ title(Sectoral FDI in Tunisia)) (line ISICSecondary year if gwf_country=="Tunisia" & /*
				*/ ISICTertiary~=., color(blue)) (line ISICTertiary year if gwf_country=="Tunisia" & ISICTertiary~=., /*
				*/ color(green) ylab(,glcolor(gs15)) legend(label(1 "Primary") label(2 "Secondary") /*
				*/ label(3 "Tertiary")  pos(11) ring(0) col(1)))
			
		 forval i = 1(1)$m {
			import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
			qui:sort cow year
			qui:merge cow  year using "$dir\temp.dta"
			tab _merge
			global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
			qui:tsset cow year
			xtserial cub_primaryfdigdp gwf_personal $cvarlist
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist, re 
			gen s1=e(sample)==1
			egen max = max(l1res),by(cow)
			gen countryOIL = max>1
			tab countryOIL if s1==1
			egen tag = tag(cow) if s1==1
			tab countryOIL if tag==1
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist, re 
			est store impMAIN`i'
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist if max<1, re 
			est store impNO`i'
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist if max>1, re 
			est store impOIL`i'
		}
		
		egen max_pers = max(gwf_pers),by(cow)
		tab max_pers if countryOIL==1 & tag==1
		tab max_pers if countryOIL==0 & tag==1

		gen hi =.
		gen lo =.
		gen mhi  =.
		gen mlo =.
		gen b =.
		gen se =.
		gen count =_n
		gen model = ""

		global count=3									/* number of specifications to test */
		global ac = $count
		global v = "gwf_personal"						/* name of variable of interest to plot */
		local mod = "MAIN NO OIL"
		foreach md of local mod {
			global imp ="imp`md'"
			jwmi
		}
 	 	gen e=round(b,.001)
		twoway (scatter count b if count<=3,ylab(6(1)$ac,glcolor(gs16)) mlab(e) mlabpos(12) xlab(-.05(.05).1) ///
		mcolor(gs6) msymbol(plus) yscale(range(0.75 3.25)) xtitle(Personalist estimate) xline(0,lpat(dash))) ///
		(rspike hi lo count if count<=3, horizontal ytitle("") title(Countries with low/high oil reserves,size(medium)) ///
		ylab(1 `""35 High oil" "countries""' 2 `""26 Low oil" "countries""' 3 `""All 61  " "countries""')  lcolor(gs6) lwidth(medthin) legend(off) scheme(lean2))		///
		(rspike mhi mlo count if count<=3, lwidth(thick) lcolor(gs6) horizontal saving(h2.gph,replace))
		gr combine h1.gph h2.gph
		graph export "$dir\golden\Sectoral-OilvNo.pdf", as(pdf) replace
		graph export "$dir\golden\ISQ-Figure-7.png", as(png) replace

		erase h1.gph
		erase h2.gph

		twoway (kdensity cub_prim if countryOIL==0 & s1==1,bw(.05) color(blue) ytitle(Density,height(6)) ///
		xtitle(Primary FDI)) (kdensity cub_prim if countryOIL==1 & s1==1,bw(.05) legend(lab(1 "Low oil") ///
		lab(2 "High oil") pos(3) col(1) ring(0)) color(black) scheme(lean2) ylab(,glcolor(gs16)))
		
		******************
		*** Figure L-1 ***
		******************
		* T-test: HiOilNoPers has less Primary than LoOilYesPers * 
			forval i = 1(1)$m {
			import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
			rename cub_primary cub`i'_primary
			sort cow year
			save mitemp`i',replace
			}		
			use mitemp1,clear
			sort cow year
			forval i = 2(1)10 {
					merge cow year using mitemp`i'
					tab _merge
					drop _merge
					sort cow year
					save mitemp,replace
					erase mitemp`i'.dta
			}
			erase mitemp1.dta
			use mitemp,clear
			qui:sort cow year
			qui:merge cow  year using "$dir\temp.dta"
			tab _merge
			global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
			qui:tsset cow year
			gen meanprimary =  (cub1_primary+ cub2_primary+  cub3_primary + cub4_primary + cub6_primary + cub7_primary + cub8_primary + cub9_primary + cub10_primary)/10
			xtserial meanprimary gwf_personal $cvarlist
			qui:xtregar meanprimary gwf_personal $cvarlist, re 
			gen s1=e(sample)==1
			egen max = max(l1res),by(cow)
			gen countryOIL = max>1
			tab countryOIL if s1==1
			egen tag = tag(cow) if s1==1
			tab countryOIL if tag==1
			gen hiOilnoPers = countryOIL==1 & gwf_pers==0 & s1==1
			gen loOilyesPers = countryOIL==0 & gwf_pers==1 & s1==1
			egen mmean = mean(meanprimary),by(gwf_casename)
			* Cases *
			egen tag2 = tag(gwf_casename) if (loOilyesPers==1 | hiOilnoPers==1) & s1==1  
			tab loOilyes if tag2==1
			list gwf_casename mmean if tag2==1 & loOilyes==1,clean noobs
			list gwf_casename mmean if tag2==1 & hiOilnoPers==1,clean noobs
			* T-test *
			ttest meanprimary if loOilyesPers==1 | hiOilnoPers==1, by(gwf_pers)
			twoway (kdensity meanprimary if loOilyesPers==1) (kdensity meanprimary if hiOilnoPers==1,scheme(lean2) ///
				ytitle(Density) xtitle(Primary FDI) ylab(,glcol(gs12)) legend(lab(1 "Personalist, low oil") ///
				lab(2 "Non-personalist, high oil") pos(6) col(2) ring(1)) ///
				text(4  .25 " {bf:{&mu} =0.148}",linegap(-1.3)place(n)) ///
				text(3  -.025 " {bf:{&mu} =0.119}",linegap(-1.3)place(n)))
			erase mitemp.dta
			graph export "$dir\golden\ttest-HiLo.pdf", as(pdf) replace
	
		****************
		*** Figure 6 ***
		****************
		*** Different estimators + 2SLS ***	
		forval i = 1(1)$m {
			import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
			qui:sort cow year
			qui:merge cow  year using "$dir\temp.dta"
			keep if cub_prim~=.
			tab _merge
			recode inst (.=0)
			qui:global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
			qui:tsset cow year
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist, re 
			est store impMAIN`i'
			qui:xtivreg cub_primaryfdigdp (gwf_personal=inst) $cvarlist, re ec vce(cluster cow) regress
			est store impRE`i'
			qui:xtivreg cub_primaryfdigdp (gwf_personal=inst) $cvarlist, re ec vce(cluster cow)
			est store impREIV`i'
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist, fe 
			est store impAR1FE`i'
			qui:xtivreg2 cub_primaryfdigdp gwf_personal $cvarlist, fe bw(2) rob  
			est store impHACFE`i'
			qui:xtivreg2 cub_primaryfdigdp (gwf_personal=inst) $cvarlist, fe bw(2) rob
			est store impHACFEIV`i'
		}
 		gen hi =.
		gen lo =.
		gen mhi  =.
		gen mlo =.
		gen b =.
		gen se =.
		gen count =_n
		gen model = ""

 		
	 	global count=6									/* number of specifications to test */
		global ac = $count
		global v = "gwf_personal"						/* name of variable of interest to plot */
		local mod = "MAIN RE REIV AR1FE HACFE HACFEIV"
		foreach md of local mod {
			global imp ="imp`md'"
			jwmi
		}
		gen e=round(b,.001)
		twoway (scatter count b if count<=6,ylab(3(1)$ac,glcolor(gs16)) mlab(e) mlabpos(12) xlab(0(.05).15) ///
		mcolor(gs6) msymbol(plus) yscale(range(0.75 6.25)) ///
		xtitle(Personalist estimate) xline(0,lpat(dash))) (rspike hi lo count if count<=6, horizontal ytitle("") ///
		title(Different estimators,size(medium)) ///
		ylab(1 `""2SLS" "FE  "  "HAC""' 2 `""FE  " "HAC""' 3 `""FE   " "AR(1)""'  ///
		4 `""2SLS " "RE   " "cluster""' 5 `""RE   " "cluster""'  6 `""RE  " "AR(1)""') ///
		lcolor(gs6) lwidth(medthin) legend(off) scheme(lean2))		///
		(rspike mhi mlo count if  count<=6, lwidth(thick) lcolor(gs6) horizontal)  
		graph export "$dir\golden\Robust-Estimators.pdf", as(pdf) replace
		graph export "$dir\golden\ISQ-Figure-6.png", as(png) replace

****************
*** Figure 5 ***
****************
		*** First stage ****
		forval i = 1(1)$m {
			import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
			qui:sort cow year
			qui:merge cow  year using "$dir\temp.dta"
			qui:tab _merge
			global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 ldevelopingfdi"
			qui:tsset cow year
			qui:xtivreg2 gwf_personal inst  $cvarlist if cub_prim~=., fe bw(2) rob 
			est store impFIRST`i'
			test inst
		}
 		gen hi =.
		gen lo =.
		gen mhi  =.
		gen mlo =.
		gen b =.
		gen se =.
		gen count =_n
		gen model = ""
		gen variable = ""

				global count=9								/* number of specifications to test */
				global ac = $count
				global imp ="impFIRST"
				local var = "inst allexp gtime lgdpcap lpop lopenness grow incidencev413 ldevelopingfdi"
				foreach cvar of local var {
						global v = "`cvar'"						/* name of variable of interest to plot */
						qui:replace variable = "$v" if count==$count
						jwmi 
				}
				gen e=round(b,.001)
				gen s=round(se,.001)
				browse variable e s hi lo
				
				twoway (scatter count b if count<=9,ylab(1(1)$ac,glcolor(gs16)) mlab(e) mlabpos(12) xlab(-.4(.2).6) ///
				mcolor(gs6) msymbol(plus) yscale(range(0.75 9.25))  xtitle(Coefficient estimate) xline(0,lpat(dash))) ///
				(rspike hi lo count if count<=9, horizontal ytitle("") title("First stage regression",size(medium)) ///
				ylab(1 "Total Developing FDI" 2 "Civil conflict"  ///
				3 "Annual GDP Growth" 4 "Trade (log)" 5 "Population (log)" 6 "GDP per cap. (log)" ///
				7 "Regime duration" 8 "Expropriations" 9 "{bf:Instrument}")  lcolor(gs6) lwidth(medthin) ///
				legend(off) scheme(lean2)) (rspike mhi mlo count if count<=9, lwidth(thick) lcolor(gs6) horizontal ///
				text(1 .4 "F statistic{sub:Instrument} = 46",size(small)))
				graph export "$dir\golden\First.pdf", as(pdf) replace
				graph export "$dir\golden\ISQ-Figure-5.png", as(png) replace


	*********************************
	*** Appendix S: Summary Stats ***
	*********************************
 	label var lgdpcap  "GDP per cap. (log)"
	label var lgdp  "GDP (log)"
	label var lpop  "Population (log)"
	label var lopenness  "Trade open (log)"
	label var grow "Annual GDP Growth"
	label var allexp "Expropriations"
	label var incidencev413 "Civil conflict"
	label var meanres  "Pre-1980 oil reserves per cap. (log) "
	label var ldevelopingfdi "Total developing FDI"
	label var gwf_personal "Personalist"
	label var gtime "Regime duration (log)"
	label var asia "Asia"
	label var ssa "Sub-Saharan Africa"
	label var america "Americas"
	label var easia "East Asia"
	global m = 10
	matrix store = J($m,4,.)							/* matrix for storing stats */		
	forval i = 1(1)$m {
			import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
			qui:sort cow year
			qui:merge cow  year using "$dir\temp.dta"
			qui:tab _merge
			global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
			qui:tsset cow year
			qui:reg cub_primary gwf_personal $cvarlist 
			keep if e(sample)==1
			keep cub_primary gwf_personal $cvarlist 
			qui:sum cub_primary
			matrix store[`i',1]=r(mean)
			matrix store[`i',2]=r(sd) 
			matrix store[`i',3]=r(min)
			matrix store[`i',4]=r(max)
		}
	matrix c = J(1,$m,1)							/* matrix for obtaining columns sums */		
	matrix means = (c*store)/$m						/* calculate the column means */
	matrix colnames means = mean sd min max
	matrix list means
	
	*****************
	*** Table S-1 ***
	*****************
	sutex gwf_personal allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ///
	ldevelopingfdi asia america easia ssa, labels digits(2) minmax


	****************************************
	*** Appendix A: OLS robustness tests ***
	****************************************
	**************
	* Figure A-1 *  Robustness tests
	**************
		forval i = 1(1)$m {
 			import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
			qui:sort cow year
			qui:save temp_primary,replace
			import delimited using "$dir\imputed-fdi\secondary`i'.csv",clear
			qui:sort cow year
			qui:save temp_secondary,replace
			import delimited using "$dir\imputed-fdi\tertiary`i'.csv",clear
			qui:sort cow year
			merge cow year using temp_primary
			qui:drop _merge
			qui:sort cow year
			merge cow year using temp_secondary
			qui:rename _merge sector_merge
			qui: sort cow year
			qui:merge cow  year using "$dir\temp.dta"
			qui:keep if sector_merge==3
			qui:drop sector_merge // brib*
			
			gen cub_rpfdi  = (abs(rpfdi))^(1/3)
			replace cub_rpfdi = -1*cub_rpfdi if rpfdi<0
			replace cub_rpfdi=cub_rpfdi/50 /* rescale to same scale as cub_primary */
			*hist cub_rpfdi if gwf_pers~=., bin(50)
			gen log_rgdp = ln(rgdpo)
			gen time  = year-1979
			gen time2 = time^2
			gen time3 = time^3
	
			global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
			tsset cow year
			* Base *
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist, re   
			est store impRob0`i'
			* No controls *
			qui:xtregar cub_primaryfdigdp gwf_personal, re   
			est store impRob1`i'
			* Primary FDI without GDP in denominator *
			qui:xtregar cub_rpfdi gwf_personal allexp gtime log_rgdp lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa, re  /* no controls */
			est store impRob2`i'
			* Non-linear time trend *
			qui:xtregar cub_primaryfdigdp gwf_personal time* $cvarlist, re  
			est store impRob3`i'
			* Other sector FDI *
			qui:xtregar cub_primaryfdigdp gwf_personal cub_secondary cub_tertiary $cvarlist,re 
			est store impRob4`i'
			* Other regime types
			qui:xtregar cub_primaryfdigdp gwf_personal gwf_monarchy gwf_mil gwf_party $cvarlist,re 
			est store impRob5`i'
			* Just dictatorships *
			qui:xtregar cub_primaryfdigdp gwf_pers $cvarlist if gwf_regime~="NA",re
			est store impRob6`i'
			* Personalism index *
			qui:xtregar cub_primaryfdigdp pers $cvarlist,re
			est store impRob7`i'
			* Add PolCon to specification *
			qui:xtregar cub_primaryfdigdp gwf_pers $cvarlist lpolcon,re
			est store impRob8`i'
		}
 		gen hi =.
		gen lo =.
		gen mhi  =.
		gen mlo =.
		gen b =.
		gen se =.
		gen count =_n
		gen model = ""

 		
	 	global count=9									/* number of specifications to test */
		global ac = $count
		global v = "gwf_personal"						/* name of variable of interest to plot */
		local mod = "Rob0 Rob1 Rob2 Rob3 Rob4 Rob5 Rob6 Rob8"
		foreach md of local mod {
			global imp ="imp`md'"
			jwmi
		}
		global v = "pers"						/* name of variable of interest to plot */
		global imp ="impRob7"
		jwmi
		gen e=round(b,.001)
	
		twoway (scatter count b if count<=10,ylab(1(1)$ac,glcolor(gs16)) mlab(e) ///
		mlabpos(12) xlab(0(.02).1)  mcolor(gs6) msymbol(plus) yscale(range(0.75 8.5))  ///
		xtitle(Coefficient estimate) xline(0,lpat(dash)))  (rspike hi lo count if count<=9, ///
		horizontal ytitle("") title("Robustness tests",size(medium)) subtitle("RE, AR(1)",size(small)) ///
		ylab(1 "Add Polcon" 2"Personalism index" 3 "Autocracies only"   4 "+ autocratic types" ///
		5 "+ other sectoral FDI" 6 "Non-linear time trend" 7 `" "Prim. FDI w/out" "GDP denominator" "'  ///
		8 "No controls" 9 "Base" )  lcolor(gs6) lwidth(medthin)  legend(off) scheme(lean2)) ///
		(rspike mhi mlo count if count<=9, lwidth(thick) lcolor(gs6) horizontal)
		graph export "$dir\golden\OLS-Robust.pdf", as(pdf) replace
		
		******************
		*** Figure A-2 ***
		******************
		*** PRS `Law and Order' control with imputed data for 1984-2010 ***
		global cvarlist="laworderi allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
		set more off
		global m = 10									/* number of imputated data sets, estimates to average */
 
			forval i = 1(1)$m {
				import delimited using "$dir\imputed-fdi\law`i'.csv",clear
				qui:sort cow year
				qui:merge cow  year using "$dir\temp.dta"
				tab _merge
				drop _merge
 				global cvarlist="laworderi allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
				qui:tsset cow year
				xtserial cub_primaryfdigdp gwf_personal $cvarlist
				qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist, re 
				est store primaryAR1RE`i'
			}
			
				gen hi =.
				gen lo =.
				gen mhi  =.
				gen mlo =.
				gen b =.
				gen se = .
				gen count =_n
				gen model = ""
				gen variable = ""			
				global count=11								/* number of specifications to test */
				global ac = $count
				global imp ="primaryAR1RE"
				local var = "gwf_pers laworderi allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi"
				foreach cvar of local var {
						global v = "`cvar'"						/* name of variable of interest to plot */
						qui:replace variable = "$v" if count==$count
						jwmi 
				}
				gen e=round(b,.001)
				gen s=round(se,.001)
				browse variable e s hi lo
				
				twoway (scatter count b if count<=11,ylab(1(1)$ac,glcolor(gs16)) mlab(e) mlabpos(12) xlab(-.05(.05).1) ///
				mcolor(gs6) msymbol(plus) yscale(range(0.75 10.25))  xtitle(Coefficient estimate) xline(0,lpat(dash))) ///
				(rspike hi lo count if count<=11, horizontal ytitle("") title(Personalist and Primary FDI,size(medium)) ///
				ylab(1 "Total Developing FDI" 2 "Oil reserves per cap. (log)" 3 "Civil conflict"  ///
				4 "Annual GDP Growth" 5 "Trade (log)" 6 "Population (log)" 7 "GDP per cap. (log)" ///
				8 "Regime duration" 9 "Expropriations" 10 "Law and order" 11"{bf:Personalist}")  lcolor(gs6) lwidth(medthin) ///
				legend(off) scheme(lean2))
				graph export "$dir\golden\OLS-PRS-LawOrder.pdf", as(pdf) replace


	*****************************************************
	*** Appendix B: Transformations of the DV ***
	*****************************************************	
 	import delimited using "$dir\imputed-fdi\primary1.csv",clear
	qui:sort cow year
	rename cub_primary cubprimary1
	save imptemp,replace
	forval i = 2(1)$m {
 		import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
		qui:sort cow year
		qui:merge cow year using imptemp
		qui:drop _merge
		rename cub_primary cubprimary`i'
		qui:sort cow year
		qui:save imptemp,replace
	}
	sum cubprimary*
	qui:merge cow year using "$dir\temp.dta"
	tsset cow year
	egen cub_primaryfdigdp = rowmean(cubprimary*)
	sum cub*
	gen primaryfdigdp = (abs(cub_primaryfdigdp))^3
	gen log_primaryfdigdp = ln(1+abs(primaryfdigdp*100))
	gen quad_primaryfdigdp = primaryfdigdp^(1/4)
	local t = "primaryfdigdp log_primaryfdigdp quad_primaryfdigdp"
	foreach type of local t {
		replace `type' = `type'*-1 if cub_primaryfdigdp<0
	}
	swilk primaryfdigdp log_primaryfdigdp cub_primaryfdi quad_primaryfdigdp
	sfrancia primaryfdigdp log_primaryfdigdp cub_primaryfdi quad_primaryfdigdp,boxcox
	
	******************
	*** Figure B-1 ***
	******************
	* Histograms *
	hist primaryfdigdp, bin(75) color(gs1) ytitle("") xtitle(No transformation, size(large)) saving(h1, replace) 
	hist log_primaryfdigdp, color(gs5) ytitle("") bin(75) xtitle(Log transformation, size(large)) saving(h2, replace) 
	hist cub_primaryfdigdp, color(gs9) ytitle("") bin(75) xtitle(Cube root transformation, size(large)) saving(h3, replace) 
	hist quad, bin(75) color(gs13) ytitle("") bin(75) xtitle(Quadratic root transformation, size(large))  saving(h4, replace) 
 	graph combine h1.gph h2.gph h3.gph h4.gph, col(2) xsize(2) ysize(1.2) scheme(lean2) /// 
		l1title("      Density                                     Density")
	graph export "$dir\golden\PFDI-Distribution.pdf", as(pdf) replace
 
	******************
	*** Figure B-2 ***
	****************** 	* Descriptive Stats, by regime * 
 	cibar primaryfdigdp, over1(allregime) graphopts(saving(f1, replace) title(No transformation) scheme(lean2) /*
	*/ ytitle(FDI (%GDP)) xlab(1.45 "Democracy" 2.85 "Military" 4.35 "Monarchy" 5.8 "Party" /*
	*/ 7.25 "Personal") ylabel(0 (.01) .03,glcolor(gs15)) legend(off)) barcolor(gs15 gs14 gs13 gs12 gs11) bargap(45)
	
	cibar log_primaryfdigdp, over1(allregime) graphopts( saving(f2, replace) title(Log transformation) scheme(lean2) /*
	*/ ytitle(FDI (%GDP)) xlab(1.45 "Democracy" 2.85 "Military" 4.35 "Monarchy" 5.8 "Party" /*
	*/ 7.25 "Personal") ylabel(0 (.2) .8,glcolor(gs15)) legend(off)) barcolor(gs15 gs14 gs13 gs12 gs11) bargap(45)
	
	cibar cub_primaryfdigdp, over1(allregime) graphopts(saving(f3, replace) title(Cube root) scheme(lean2) /*
	*/ ytitle(FDI (%GDP)) xlab(1.45 "Democracy" 2.85 "Military" 4.35 "Monarchy" 5.8 "Party" /*
	*/ 7.25 "Personal") ylabel(0 (.05) .2,glcolor(gs15)) legend(off)) barcolor(gs15 gs14 gs13 gs12 gs11) bargap(45)
	
	cibar quad_primaryfdigdp, over1(allregime) graphopts(saving(f4, replace) title(Quadratic root) scheme(lean2) /*
	*/ ytitle(FDI (%GDP)) xlab(1.45 "Democracy" 2.85 "Military" 4.35 "Monarchy" 5.8 "Party" /*
	*/ 7.25 "Personal") ylabel(0 (.1) .3,glcolor(gs15)) legend(off)) barcolor(gs15 gs14 gs13 gs12 gs11) bargap(45)
	
	graph combine f1.gph f2.gph f3.gph f4.gph, iscale(.35) col(2) xsize(6) ysize(5)   scheme(lean2) /*
	*/ title("Primary FDI by regime type", pos(6) size(small)) 
	graph export "$dir\golden\PFDI-Sample.pdf", as(pdf) replace
	erase imptemp.dta
	
	******************
	*** Figure B-3 ***
	******************
		forval i = 1(1)$m {
 			import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
			qui:sort cow year
			qui:merge cow  year using "$dir\temp.dta"
			
			gen primaryfdigdp = (abs(cub_prim))^3
			gen log_primaryfdigdp = ln(1+abs(primaryfdigdp))
			gen quad_primaryfdigdp = primaryfdigdp^(1/4)
			local t = "primaryfdigdp log_primaryfdigdp quad_primaryfdigdp"
			foreach type of local t {
				replace `type' = `type'*-1 if cub_prim<0
			}
			swilk primaryfdigdp log_primaryfdigdp cub_primaryfdi quad_primaryfdigdp
	
			global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
			tsset cow year
			* Base: cube root *
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist, re   
			est store impRob0`i'
			* No transformation *
			qui:xtregar primaryfdigdp gwf_personal $cvarlist, re   
			est store impRob1`i'
			* Log transformation *
			qui:xtregar log_primaryfdigdp gwf_personal $cvarlist, re   
			est store impRob2`i'
			* Quadratic root *
			qui:xtregar quad_primaryfdigdp gwf_personal $cvarlist, re   
			est store impRob3`i'
		}
 		gen hi =.
		gen lo =.
		gen mhi  =.
		gen mlo =.
		gen b =.
		gen se =.
		gen count =_n
		gen model = ""

 		capture program drop jwmi
		program define jwmi
				matrix c = J(1,$m,1)							/* matrix for obtaining columns sums */		
					* Get and store the estimates *
				matrix est = J($m,2,.)							/* place to store estimates */
				forval i = 1/10{
					qui:est restore $imp`i'						/* get estimate */
					qui:nlcom _b[$v],post
					matrix beta =e(b)
					matrix var = e(V)
					matrix est[`i',1]==beta[1,1]
					matrix est[`i',2]==var[1,1]
				}
				matrix colnames est = beta var
				*matrix list est									/* show the estimates from tests for each imputed data set */
					* Estimate of beta is the mean *
				matrix mean_b = (c*est)/$m						/* calculate the mean of b */
					* Between variance, Vb *
				matrix cvb = J($m,1,.)
				forval i = 1/$m {
					matrix x ==est[`i',1]						/* get the x_i's  */
					matrix cvb[`i',1]==(x[1,1]- mean_b[1,1])^2  /* squared deviations from mean */
				}
				matrix  vb = (c*cvb)/($m-1) 					/* sum squares and divide by n-1 */
					* Within variance, Vw *
				matrix vw = mean_b[1,2]
					*  Total variance *
				matrix tv = vw[1,1] + vb[1,1] + (vb[1,1]/$m)
					* Show the MI beta & se *
				matrix beta= mean_b[1,1]
				matrix se = sqrt(tv[1,1]) 
				matrix list beta
				matrix list se
					* Store results for graphing
				replace b = beta[1,1] if count==$count
				replace se = se[1,1] if count==$count
				replace hi =  beta[1,1] + 1.96*se[1,1] if count==$count
				replace lo =  beta[1,1] - 1.96*se[1,1] if count==$count
				replace mhi =  beta[1,1] + 1.65*se[1,1] if count==$count
				replace mlo =  beta[1,1] - 1.65*se[1,1] if count==$count
				replace model = "$imp" if count==$count
				global count=$count -1
		end
		
	 	global count=4									/* number of specifications to test */
		global ac = $count
		global v = "gwf_personal"						/* name of variable of interest to plot */
		local mod = "Rob0 Rob1 Rob2 Rob3"
		foreach md of local mod {
			global imp ="imp`md'"
			jwmi
		}
		gen e=round(b,.001)
		
		twoway (scatter count b if count<=4,ylab(1(1)$ac,glcolor(gs16)) mlab(e) ///
		mlabpos(12) xlab(0(.05).15)  mcolor(gs6) msymbol(plus) yscale(range(0.75 4.5))  ///
		xtitle(Coefficient estimate) xline(0,lpat(dash)))  (rspike hi lo count if count<=4, ///
		horizontal ytitle("") title("Different FDI transformations",size(medium)) subtitle("RE, AR(1)",size(small)) ///
		ylab(1 "Quadratic root" 2 "Natural log"  3 "No transformation" 4 "Base (cube root)" )  lcolor(gs6) lwidth(medthin)  legend(off) scheme(lean2)) ///
		(rspike mhi mlo count if count<=4, lwidth(thick) lcolor(gs6) horizontal)
		graph export "$dir\golden\OLS-FDI-Distributions.pdf", as(pdf) replace


	*****************************
	*** Appendix C: Oil data  ***
	*****************************
	******************
	*** Figure C-1 ***
	******************
	forval i = 1(1)$m {
 			import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
			qui:sort cow year
			qui:merge cow  year using "$dir\temp.dta"
			tsset cow year
			global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 ldevelopingfdi asia america easia ssa"
			* Base *
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist meanres, re   
			est store impRob0`i'
			* Add oil price *
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist meanres oil_price_2000, re   
			est store impRob1`i'
			* Lagged 5 oil reserves *
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist l5res, re   
			est store impRob2`i'
			* Lagged 1 oil reserves *
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist l1res, re   
			est store impRob3`i'
			* Lagged 5 oil rents *
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist oil5, re   
			est store impRob4`i'
			* Lagged 1 oil rents *
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist oilpc, re   
			est store impRob5`i'
			* Lagged 1 total resources *
			gen resources = ln(1+(l.total_resources_income_pc)^(1/3))
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist resources, re   
			est store impRob6`i'
		}
 		gen hi =.
		gen lo =.
		gen mhi  =.
		gen mlo =.
		gen b =.
		gen se =.
		gen count =_n
		gen model = ""
		
	 	global count=7									/* number of specifications to test */
		global ac = $count
		global v = "gwf_personal"						/* name of variable of interest to plot */
		local mod = "Rob0 Rob1 Rob2 Rob3 Rob4 Rob5 Rob6"
		foreach md of local mod {
			global imp ="imp`md'"
			jwmi
		}
		gen e=round(b,.001)
		
		twoway (scatter count b if count<=7,ylab(1(1)$ac,glcolor(gs16)) mlab(e) ///
		mlabpos(12) xlab(0(.05).15)  mcolor(gs6) msymbol(plus) yscale(range(0.75 7.5))  ///
		xtitle(Coefficient estimate) xline(0,lpat(dash)))  (rspike hi lo count if count<=7, ///
		horizontal ytitle("") title("Different resource variables",size(medium)) subtitle("RE, AR(1)",size(small)) ///
		ylab(1 "Total resources"2 "Oil rents, lag 1" 3 "Oil rents, lag 5" 4 "Reserves, lag 1" 5 "Reserves, lag 5"  6 "+ Oil price" 7 "Base (pre-1980 reserves)" )  lcolor(gs6) lwidth(medthin)  legend(off) scheme(lean2)) ///
		(rspike mhi mlo count if count<=7, lwidth(thick) lcolor(gs6) horizontal)
		graph export "$dir\golden\OLS-Resource-Variables.pdf", as(pdf) replace


	**************************************************************
	*** Appendix D: Two-stage diagnostics and Robustness tests ***
	**************************************************************
	import delimited using "$dir\imputed-fdi\primary5.csv",clear   /* we aren't modeling imputed FDI in this section, so no need to use 10 mi data sets */
	qui:sort cow year
	qui:merge cow  year using "$dir\temp.dta"
	recode inst (.=0)
	tsset cow year
	global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
	qui reg cub_primary gwf_personal inst $cvarlist
	gen s1=e(sample)
	*** US and Soviet covert intervention data ***
	gen uscia = 0 if s1==1
	gen sovietkgb =0 if s1==1
	replace uscia = 1 if gwf_casename=="Argentina 76-83" | gwf_casename=="Colombia 58-NA" | gwf_casename=="Egypt 52-NA" ///
	| gwf_casename=="Honduras 81-NA" | gwf_casename=="Jordan 46-NA" | gwf_casename=="Korea, South 61-87" ///
	| gwf_casename=="Korea, South 87-NA" | gwf_casename=="Panama 89-NA" | gwf_casename=="Paraguay 54-93"  /// 
	| gwf_casename=="Saudi Arabia 27-NA"
	replace sovietkgb = 1 if gwf_casename=="Costa Rica 49-NA" | gwf_casename=="Egypt 52-NA" | gwf_casename=="Laos 75-NA" 
	
	******************
	*** Figure D-1 ***
	******************
	*** Instrument strength ***
	tab gwf_pers inst if s1==1,col
	reg gwf_personal inst $cvarlist if s1==1 
	avplot inst,xtitle(e(Excluded instrument | X)) ytitle(e(Personalist | X))
 	graph export "$dir\golden\Instrument-Strength.pdf", as(pdf) replace
		
	******************
	*** Figure D-2 ***
	******************
	*** Pre-1980 FDI ***
	gen ldist = ln(wdistance)
	hist pre80fdi if s1==1
	egen caseid = group(gwf_casename) if s1==1
	egen min = min(year) if s1==1,by(caseid)
	egen maxinst = max(inst) if s1==1,by(caseid)
	ttest pre80fdi if s1==1 & min==year,by(maxinst)
	logit maxinst pre80fdi if year==min & s1==1,r
	est store pre1
	logit maxinst pre80fdi lgdpcap lpop ldist meanres  if year==min & s1==1,r
	est store pre2
	logit maxinst pre80fdi lgdpcap lpop ldist oil5pc  if year==min & s1==1,r
	est store pre3
	krls inst pre80fdi lgdpcap lpop meanres ldist if year==min & s1==1,d(d)
	hist d_mean
	twoway lpolyci d_mean lgdpcap
	drop d_*
	label var pre80fdi "{bf:Pre-1980 FDI}"
	label var ldist `" "Distance    " "to 20 richest " "economies (log)" "'
	label var oil5pc `" "Oil rents " "{it:t-5}, (log) " "'
	label var meanreserves `" "Oil reserves " "pre-1980 (log)" "'
	label var lgdpcap  `" "GDP per cap." "(log)      " "'
	label var lpop  `" "Population" "(log)    " "'

	cibar pre80fdi if s1==1 & min==year,over1(maxinst) barcolor(gs13 gs10) bargap(45) ///
	graphopts(xlab(1.45 "Unified seizure" 2.85 "Divided seizure") ytitle("Mean level of Total FDI, % GDP", height(3)) ///
	ylabel(0 (.5) 2,glcolor(gs15)) xscale(range (0.75 3.7)) legend(off) scheme(lean2) title("Pre-1980 FDI",size(medsmall)) saving(h1.gph,replace) ///
	graphr(margin(1 1 9 1)))
	coefplot (pre1, msymbol(D)) (pre2, msymbol(T)) (pre3, msymbol(Oh)), title("Pre-1980 FDI and Divided Seizure")/*
	*/ scheme(lean2) drop(_cons) order(pre80fdi lgdp lgdpcap lpop lopenness) scale(.75) xlab(-1(.5) 1.5)/*
	*/ xline(0, lpattern(dash)) grid(glcolor(gs15)) mfcolor(white)   /*
	*/ legend(label(3 "Bivariate") label(6 "Structural") label(9 "Oil rents") pos(8) ring(0) col(1))  /*
	*/ levels(95 90) xtitle("  Coefficient estimate", height(3)) saving(h2.gph,replace)   
	graph combine h1.gph h2.gph, xsize(3.5) ysize(2) rows(1)
 	graph export "$dir\golden\Pre80-FDI.pdf", as(pdf) replace
	drop min caseid

	
	******************
	*** Figure D-3 ***
	******************
	*** Robustness tests with IV ***  
		forval i = 1(1)$m {
 			import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
			qui:sort cow year
			qui:save temp_primary,replace
			import delimited using "$dir\imputed-fdi\secondary`i'.csv",clear
			qui:sort cow year
			qui:save temp_secondary,replace
			import delimited using "$dir\imputed-fdi\tertiary`i'.csv",clear
			qui:sort cow year
			merge cow year using temp_primary
			qui:drop _merge
			qui:sort cow year
			merge cow year using temp_secondary
			qui:rename _merge sector_merge
			qui: sort cow year
			qui:merge cow  year using "$dir\temp.dta"
			qui:keep if sector_merge==3
		 	gen primaryfdigdp = (abs(cub_prim))^3
			gen quad_primaryfdigdp = primaryfdigdp^(1/4)
			replace quad = quad*-1 if cub_primary<0
			recode inst (.=0)

			gen time  = year-1979
			gen time2 = time^2
			gen time3 = time^3
			
			*** US and Soviet covert intervention data ***
			gen uscia = 0 
			gen sovietkgb =0
			replace uscia = 1 if gwf_casename=="Argentina 76-83" | gwf_casename=="Colombia 58-NA" | gwf_casename=="Egypt 52-NA" ///
			| gwf_casename=="Honduras 81-NA" | gwf_casename=="Jordan 46-NA" | gwf_casename=="Korea, South 61-87" ///
			| gwf_casename=="Korea, South 87-NA" | gwf_casename=="Panama 89-NA" | gwf_casename=="Paraguay 54-93"  /// 
			| gwf_casename=="Saudi Arabia 27-NA"
			replace sovietkgb = 1 if gwf_casename=="Costa Rica 49-NA" | gwf_casename=="Egypt 52-NA" | gwf_casename=="Laos 75-NA"
	
			global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413  ldevelopingfdi"
			tsset cow year
			* Base *
			qui:xtivreg2 cub_primaryfdigdp (gwf_personal=inst) $cvarlist, fe bw(2) rob  
			est store impRob0`i'
			* Add other seizure types *
			qui:xtivreg2 cub_primaryfdigdp (gwf_personal=inst)seizure_coup seizure_reb seizure_foreign $cvarlist, fe bw(2) rob 
			est store impRob1`i'
			* Add cia/soviet interventions *
			qui:xtivreg2 cub_primaryfdigdp (gwf_personal=inst) uscia sovietkgb $cvarlist, fe bw(2) rob 
			est store impRob2`i'
			* Fewer controls *
			qui:xtivreg2 cub_primaryfdigdp (gwf_personal=inst) allexp gtime, fe bw(2) rob   
			est store impRob3`i'
			* Quad not cub DV transformation *
			qui:xtivreg2 quad_primaryfdigdp (gwf_personal=inst) $cvarlist, fe bw(2) rob  
			est store impRob4`i'
			* Non-linear time trend *
			qui:xtivreg2 cub_primaryfdigdp (gwf_personal=inst) time* $cvarlist, fe bw(2) rob   
			est store impRob5`i'
			* Other regime types
			qui:xtivreg2 cub_primaryfdigdp (gwf_personal=inst) gwf_monarchy gwf_mil gwf_party $cvarlist, fe bw(2) rob  
			est store impRob6`i'
			* Add Polcon
			qui:xtivreg2 cub_primaryfdigdp (gwf_personal=inst) $cvarlist lpolcon, fe bw(2) rob  
			est store impRob7`i'
			* Personalism index *
			qui:xtivreg2 cub_primaryfdigdp (pers=inst) $cvarlist, fe bw(2) rob  
			est store impRob8`i'
		}
 		gen hi =.
		gen lo =.
		gen mhi  =.
		gen mlo =.
		gen b =.
		gen se =.
		gen count =_n
		gen model = ""

 		capture program drop jwmi
		program define jwmi
				matrix c = J(1,$m,1)							/* matrix for obtaining columns sums */		
					* Get and store the estimates *
				matrix est = J($m,2,.)							/* place to store estimates */
				forval i = 1/10{
					qui:est restore $imp`i'						/* get estimate */
					qui:nlcom _b[$v],post
					matrix beta =e(b)
					matrix var = e(V)
					matrix est[`i',1]==beta[1,1]
					matrix est[`i',2]==var[1,1]
				}
				matrix colnames est = beta var
				*matrix list est									/* show the estimates from tests for each imputed data set */
					* Estimate of beta is the mean *
				matrix mean_b = (c*est)/$m						/* calculate the mean of b */
					* Between variance, Vb *
				matrix cvb = J($m,1,.)
				forval i = 1/$m {
					matrix x ==est[`i',1]						/* get the x_i's  */
					matrix cvb[`i',1]==(x[1,1]- mean_b[1,1])^2  /* squared deviations from mean */
				}
				matrix  vb = (c*cvb)/($m-1) 					/* sum squares and divide by n-1 */
					* Within variance, Vw *
				matrix vw = mean_b[1,2]
					*  Total variance *
				matrix tv = vw[1,1] + vb[1,1] + (vb[1,1]/$m)
					* Show the MI beta & se *
				matrix beta= mean_b[1,1]
				matrix se = sqrt(tv[1,1]) 
				matrix list beta
				matrix list se
					* Store results for graphing
				replace b = beta[1,1] if count==$count
				replace se = se[1,1] if count==$count
				replace hi =  beta[1,1] + 1.96*se[1,1] if count==$count
				replace lo =  beta[1,1] - 1.96*se[1,1] if count==$count
				replace mhi =  beta[1,1] + 1.65*se[1,1] if count==$count
				replace mlo =  beta[1,1] - 1.65*se[1,1] if count==$count
				replace model = "$imp" if count==$count
				global count=$count -1
		end
	 	global count=8									/* number of specifications to test */
		global ac = $count
		global v = "gwf_personal"						/* name of variable of interest to plot */
		local mod = "Rob0 Rob1 Rob2 Rob3 Rob4 Rob5 Rob6 Rob7"
		foreach md of local mod {
			global imp ="imp`md'"
			jwmi
		}
		global v = "pers"						/* name of variable of interest to plot */
		global imp ="impRob8"
		jwmi
		gen e=round(b,.001)
	
		twoway (scatter count b if count<=9,ylab(1(1)$ac,glcolor(gs16)) mlab(e) ///
		mlabpos(12) xlab(0(.05).15)  mcolor(gs6) msymbol(plus) yscale(range(0.75 9.5))  ///
		xtitle(Coefficient estimate) xline(0,lpat(dash)))  (rspike hi lo count if count<=9, ///
		horizontal ytitle("") title("IV-2SLS tests",size(medium)) subtitle("FE, HAC errors",size(small)) ///
		ylab(1 "Personalism index" 2 "Add Polcon" 3"+ Other regime types" 4 "Non-linear time trend" ///
		5 "Quadratic root DV" 6 "Fewer controls" 7 `" "+ Foreign" "interventions" "'  ///
		8 "+ Seizure types" 9 "Base")  lcolor(gs6) lwidth(medthin)  legend(off) scheme(lean2)) ///
		(rspike mhi mlo count if count<=9, lwidth(thick) lcolor(gs6) horizontal saving(h1.gph,replace))
			
			
		forval i = 1(1)$m {
 			import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
			qui:sort cow year
			qui:save temp_primary,replace
			import delimited using "$dir\imputed-fdi\secondary`i'.csv",clear
			qui:sort cow year
			qui:save temp_secondary,replace
			import delimited using "$dir\imputed-fdi\tertiary`i'.csv",clear
			qui:sort cow year
			merge cow year using temp_primary
			qui:drop _merge
			qui:sort cow year
			merge cow year using temp_secondary
			qui:rename _merge sector_merge
			qui: sort cow year
			qui:merge cow  year using "$dir\temp.dta"
			qui:keep if sector_merge==3
		 	gen primaryfdigdp = (abs(cub_prim))^3
			gen quad_primaryfdigdp = primaryfdigdp^(1/4)
			replace quad = quad*-1 if cub_primary<0
			recode inst (.=0)

			gen time  = year-1979
			gen time2 = time^2
			gen time3 = time^3
			
			*** US and Soviet covert intervention data ***
			gen uscia = 0 
			gen sovietkgb =0
			replace uscia = 1 if gwf_casename=="Argentina 76-83" | gwf_casename=="Colombia 58-NA" | gwf_casename=="Egypt 52-NA" ///
			| gwf_casename=="Honduras 81-NA" | gwf_casename=="Jordan 46-NA" | gwf_casename=="Korea, South 61-87" ///
			| gwf_casename=="Korea, South 87-NA" | gwf_casename=="Panama 89-NA" | gwf_casename=="Paraguay 54-93"  /// 
			| gwf_casename=="Saudi Arabia 27-NA"
			replace sovietkgb = 1 if gwf_casename=="Costa Rica 49-NA" | gwf_casename=="Egypt 52-NA" | gwf_casename=="Laos 75-NA"
	
			global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
			tsset cow year
			* Base *
			qui:xtivreg cub_primaryfdigdp (gwf_personal=inst) $cvarlist,re vce(cluster cow) ec
			est store impRob0`i'
			* Add other seizure types *
			qui:xtivreg cub_primaryfdigdp (gwf_personal=inst)seizure_coup seizure_reb seizure_foreign $cvarlist,re vce(cluster cow)   ec
			est store impRob1`i'
			* Add cia/soviet interventions *
			qui:xtivreg cub_primaryfdigdp (gwf_personal=inst) uscia sovietkgb $cvarlist,re vce(cluster cow)  ec
			est store impRob2`i'
			* Fewer controls *
			qui:xtivreg cub_primaryfdigdp (gwf_personal=inst) allexp gtime,re vce(cluster cow)    ec
			est store impRob3`i'
			* Quad not cub DV transformation *
			qui:xtivreg quad_primaryfdigdp (gwf_personal=inst) $cvarlist,re vce(cluster cow)  ec
			est store impRob4`i'
			* Non-linear time trend *
			qui:xtivreg cub_primaryfdigdp (gwf_personal=inst) time* $cvarlist, re vce(cluster cow)   ec
			est store impRob5`i'
			* Other regime types
			qui:xtivreg cub_primaryfdigdp (gwf_personal=inst) gwf_monarchy gwf_mil gwf_party $cvarlist,re vce(cluster cow)  ec
			est store impRob6`i'
			* Add Polcon *
			qui:xtivreg cub_primaryfdigdp (gwf_pers=inst) $cvarlist lpolcon,re vce(cluster cow)  ec
			est store impRob7`i'
			* Personalism index *
			qui:xtivreg cub_primaryfdigdp (pers=inst) $cvarlist,re vce(cluster cow)  ec
			est store impRob8`i'

		}
 		gen hi =.
		gen lo =.
		gen mhi  =.
		gen mlo =.
		gen b =.
		gen se =.
		gen count =_n
		gen model = ""

 		
	 	global count=9									/* number of specifications to test */
		global ac = $count
		global v = "gwf_personal"						/* name of variable of interest to plot */
		local mod = "Rob0 Rob1 Rob2 Rob3 Rob4 Rob5 Rob6 Rob7"
		foreach md of local mod {
			global imp ="imp`md'"
			jwmi
		}
		global v = "pers"						/* name of variable of interest to plot */
		global imp ="impRob8"
		jwmi
		gen e=round(b,.001)
	
		twoway (scatter count b if count<=9,ylab(1(1)$ac,glcolor(gs16)) mlab(e) ///
		mlabpos(12) xlab(0(.05).15)  mcolor(gs6) msymbol(plus) yscale(range(0.75 9.5))  ///
		xtitle(Coefficient estimate) xline(0,lpat(dash)))  (rspike hi lo count if count<=9, ///
		horizontal ytitle("") title("IV-2SLS tests",size(medium)) subtitle("RE, cluster errors",size(small)) ///
		ylab(1 "Personalism index" 2 "Add Polcon" 3 "+ Other regime types"   4 "Non-linear time trend" ///
		5 "Quadratic root DV" 6 "Fewer controls" 7 `" "+ Foreign" "interventions" "'  ///
		8 "+ Seizure types" 9 "Base" )  lcolor(gs6) lwidth(medthin)  legend(off) scheme(lean2)) ///
		(rspike mhi mlo count if count<=9, lwidth(thick) lcolor(gs6) horizontal saving(h2.gph,replace))
		
		gr combine h2.gph  h1.gph 
	 	graph export "$dir\golden\2SLS-Robust.pdf", as(pdf) replace
		
		
		******************
		*** Figure D-4 ***
		******************
		*** PRS `Law and Order' control ***
		global cvarlist="laworderi allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
		set more off
		global m = 10									/* number of imputated data sets, estimates to average */
 
			forval i = 1(1)$m {
				import delimited using "$dir\imputed-fdi\law`i'.csv",clear
				qui:sort cow year
				qui:merge cow  year using "$dir\temp.dta"
				tab _merge
				drop _merge
 				global cvarlist="laworderi allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
				qui:tsset cow year
				xtserial cub_primaryfdigdp gwf_pers $cvarlist
				qui:xtivreg cub_primaryfdigdp (gwf_pers=inst) $cvarlist,re vce(cluster cow)   ec 
				est store primaryAR1RE`i'
			}
			
				gen hi =.
				gen lo =.
				gen mhi  =.
				gen mlo =.
				gen b =.
				gen se = .
				gen count =_n
				gen model = ""
				gen variable = ""			
				global count=11								/* number of specifications to test */
				global ac = $count
				global imp ="primaryAR1RE"
				local var = "gwf_pers laworderi allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi"
				foreach cvar of local var {
						global v = "`cvar'"						/* name of variable of interest to plot */
						qui:replace variable = "$v" if count==$count
						jwmi 
				}
				gen e=round(b,.001)
				gen s=round(se,.001)
				browse variable e s hi lo
				
				twoway (scatter count b if count<=11,ylab(1(1)$ac,glcolor(gs16)) mlab(e) mlabpos(12) xlab(-.05(.05).1) ///
				mcolor(gs6) msymbol(plus) yscale(range(0.75 11.25))  xtitle(Coefficient estimate) xline(0,lpat(dash))) ///
				(rspike hi lo count if count<=11, horizontal ytitle("") title(Personalist and Primary FDI,size(medium)) ///
				ylab(1 "Total Developing FDI" 2 "Oil reserves per cap. (log)" 3 "Civil conflict"  ///
				4 "Annual GDP Growth" 5 "Trade (log)" 6 "Population (log)" 7 "GDP per cap. (log)" ///
				8 "Regime duration" 9 "Expropriations" 10 "Law and order" 11"{bf:Personalist}")  lcolor(gs6) lwidth(medthin) ///
				legend(off) scheme(lean2))
				graph export "$dir\golden\2SLS-PRS-LawOrder.pdf", as(pdf) replace

	***********************************************
	*** Appendix E: Outlier and Influence tests ***
	***********************************************
	******************
	*** Figure E-1 ***
	******************
	forval i = 1(1)$m {
 			import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
			qui:sort cow year
			qui:merge cow  year using "$dir\temp.dta"
			tsset cow year
			global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"		
			* Outliers *
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist, re   
			est store impRob0`i'
			qui:fit cub_primaryfdigdp gwf_pers $cvarlist if e(sample)==1
			hinflu Hi 
			centile Hi,centile(99.9 99.75 99.5)
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist if Hi<r(c_1), re
			est store impRob1`i'
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist if Hi<r(c_2), re
			est store impRob2`i'
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist if Hi<r(c_3), re
			est store impRob3`i'
			qui:bacon cub_primaryfdigdp gwf_pers $cvarlist, gen(outbacon) p(.9)
			bysort outbacon: sum Hi
			tab gwf_country if outbacon==1
			qui:xtregar cub_primaryfdigdp gwf_pers $cvarlist if outbacon==0, re
			est store impRob4`i'
			drop outbacon Hi
		}
 		gen hi =.
		gen lo =.
		gen mhi  =.
		gen mlo =.
		gen b =.
		gen se =.
		gen count =_n
		gen model = ""
		
	 	global count=5									/* number of specifications to test */
		global ac = $count
		global v = "gwf_personal"						/* name of variable of interest to plot */
		forval d=0(1)4 {
			global imp ="impRob`d'"
			jwmi
		}
		gen e=round(b,.001)
		
		twoway (scatter count b if count<=5,ylab(1(1)$ac,glcolor(gs16)) mlab(e) ///
		mlabpos(12) xlab(0(.02).12)  mcolor(gs6) msymbol(plus) yscale(range(0.75 5.5))  ///
		xtitle(Coefficient estimate) xline(0,lpat(dash)))  (rspike hi lo count if count<=5, ///
		horizontal ytitle("") title("Drop influential observations",size(medium)) ///
		ylab(1 `""Drop Bacon" "outliers""' 2 "Drop 0.5%" 3 "Drop 0.25%" 4 "Drop 0.1%"  5 "Base" ) ///
		lcolor(gs6) lwidth(medthin)  legend(off) scheme(lean2)) ///
		(rspike mhi mlo count if count<=5, lwidth(thick) lcolor(gs6) horizontal saving(h1.gph,replace))
		drop e
		
		
		forval i = 1(1)$m {
 			import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
			qui:sort cow year
			qui:merge cow  year using "$dir\temp.dta"
			tsset cow year
			global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"		
			* Drop one region at a time *
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist, re   
			est store impRob0`i'
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist if ssa==0, re
			est store impRob1`i'
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist if easia==0, re
			est store impRob2`i'
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist if meast==0, re
			est store impRob3`i'
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist if asia==0, re
			est store impRob4`i'
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist if americas==0, re
			est store impRob5`i'	
		}
 		gen hi =.
		gen lo =.
		gen mhi  =.
		gen mlo =.
		gen b =.
		gen se =.
		gen count =_n
		gen model = ""
		
	 	global count=6									/* number of specifications to test */
		global ac = $count
		global v = "gwf_personal"						/* name of variable of interest to plot */
		forval d=0(1)5 {
			global imp ="impRob`d'"
			jwmi
		}
		gen e=round(b,.001)
		
		twoway (scatter count b if count<=6,ylab(1(1)$ac,glcolor(gs16)) mlab(e) ///
		mlabpos(12) xlab(0(.02).12)  mcolor(gs6) msymbol(plus) yscale(range(0.75 6.5))  ///
		xtitle(Coefficient estimate) xline(0,lpat(dash)))  (rspike hi lo count if count<=6, ///
		horizontal ytitle("") title("Drop regions, one at a time",size(medium)) ///
		ylab(1 "Drop Americas" 2 "Drop Asia" 3 "Drop M East" 4 "Drop E Asia"  5 "Drop SSA" 6 `""Include" "all regions""' ) ///
		lcolor(gs6) lwidth(medthin)  legend(off) scheme(lean2)) ///
		(rspike mhi mlo count if count<=6, lwidth(thick) lcolor(gs6) horizontal saving(h2.gph,replace))
		drop e
		gr combine h1.gph h2.gph
		graph export "$dir\golden\OLS-Outliers.pdf", as(pdf) replace

***************************************************************
************* Appendix F: Models with no missing data ********* 
***************************************************************
	******************
	*** Figure F-4 ***
	******************
	use "$dir\temp.dta",clear
	tsset cow year
	global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
	* test autocorrelation *
	tsset cow year
	xtserial cub_Primaryfdigdp gwf_personal $cvarlist
	mixed cub_Primaryfdigdp gwf_personal  $cvarlist || cow:,residuals(ar1, t(year))  /* RE + ar1 errors  */
	mixed cub_Primaryfdigdp gwf_personal  $cvarlist || cow:,residuals(ma1, t(year))  /* RE + MA1 errors  */
	xtregar cub_Primaryfdigdp gwf_personal  $cvarlist, re /* RE + ar1  */
	gen s2=e(sample)
	est store main1
	xtregar cub_Primaryfdigdp seizure_coup seizure_reb seizure_for gwf_personal $cvarlist, re  
			* HAC errors *
			qui: ivreg2 cub_Primaryfdigdp gwf_personal $cvarlist,bw(2)r
			lincom gwf_pers
			est store er1
			* RE * 
			qui: xtreg cub_Primaryfdigdp gwf_personal $cvarlist,re 
			lincom gwf_pers
			est store er2
			* RE + cluster * 
			qui: xtreg cub_Primaryfdigdp gwf_personal $cvarlist,re vce(cluster cow)
			lincom gwf_pers
			est store er3
			* xtpcse: het + ar1 *
			qui: xtpcse cub_Primaryfdigdp gwf_personal $cvarlist,cor(ar1) het pairwise
			lincom gwf_pers
			est store er4
			* xtpcse: het + ps ar1 *
			qui: xtpcse cub_Primaryfdigdp gwf_personal $cvarlist,cor(psar1) het
			lincom gwf_pers
			est store er5
			
	* 2SLS model keeps RE but drops AR(1) and uses cluster SE instead *
		* First show the RE with no AR(1)
			xtreg cub_Primaryfdigdp   gwf_personal $cvarlist if s2==1,  re vce(cluster cow)
			xtivreg cub_Primaryfdigdp  (gwf_personal=inst) $cvarlist if s2==1,reg re vce(cluster cow) ec nosa /*OLS-RE*/
			est store main2
		* Next estimate the first stage with an RE OLS model 
			xtreg gwf_personal inst $cvarlist if s2==1, re cluster(cow) theta
			test inst
			est store main3
		* Now use the Baltagi's EC2SLS random-effects estimator with no AR(1) 
			xtivreg cub_Primaryfdigdp (gwf_personal=inst) $cvarlist if s2==1, re vce(cluster cow) first ec nosa
			est store main4
 	
	label var lgdpcap  `" "GDP per "  "cap. (log)" "'
	label var gtime `" "Regime"  "duration" "'
	label var lpop  "Population"
	label var allexp "Expropriations"
	label var lopenness  `" "Trade    "  "openness" "'
	label var grow "Growth"
	label var incidencev413 `" "Civil   "  "conflict" "'
	label var ldevelopingfdi `" "Total   "  "dev. FDI" "'
	label var gwf_personal `" "{bf:Personalist}"  "{bf:regime}    " "'
	label var meanreserves   `" "Pre-1980 oil"  "reserves   " "'
	coefplot (main1, msymbol(T) mcolor($color1) ciopts(lcol($color1 $color1))) (main4, msymbol(S) mcolor($color3) ciopts(lcol($color3 $color3))), /*
	*/ title("Primary sector FDI" " ",size(medium) height(6))  scheme(lean2) drop(_cons asia americas easia ssa) order(gwf_personal) /*
	*/ xlab(-.05 (.05) .15) ylab(,labsize(small)) xline(0, lpattern(dash)) grid(glcolor(gs15)) mfcolor(white) ysize(3) xsize(3) /*
	*/ legend(label(3 "OLS") label(6 "2SLS-IV") pos(4) ring(0) col(1) size(medsmall)) levels(95 90) /*
	*/ xtitle("  Coefficient estimate", height(6)) b1("Region dummies not reported" "Thick lines {&equiv} 90% CI; thin lines {&equiv} 95% CI", size(small))	
	graph export "$dir\golden\MainTable.pdf", as(pdf) replace
		
	*******************************************
	********** Appendix J: China FDI **********
	*******************************************
		forval i = 1(1)$m {
			qui:import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
			global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"	
			*** 2010s interaction ***
			qui:gen d20 = year>=2001 & year<=2010
			qui:gen d20Xpers = gwf_pers*d20
			tsset cow year
			qui:xtregar cub_primaryfdigdp gwf_personal d20 d20Xpers $cvarlist, re
			est store rob`i'
		}
		
 		gen hi =.
		gen lo =.
		gen mhi  =.
		gen mlo =.
		gen b =.
		gen se =.
		gen count =_n
		gen model = ""
	 	global count=1									/* number of specifications to test */
		global ac = $count
		global v = "d20X"								/* name of variable of interest to plot */
 		global imp ="rob"
		jwmi
		global count=1									/* number of specifications to test */
		global ac = $count
		global v = "gwf_pers"							/* name of variable of interest to plot */
 		global imp ="rob"
		jwmi	
		
		******************
		*** Figure J-1 ***
		******************
		*** Control for Chinese FDI ***
		forval i = 1(1)$m {
			qui:import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
			qui:sort cow year
			qui:merge cow  year using "$dir\tempchina.dta"
			qui:tsset cow year
			global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"			
			* Drop one region at a time *
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist, re 
			qui:gen log_chinafdi = ln(1+value)
			hist log_chinafdi
			qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist if log_chinafdi~=., re 
			est store china1`i'
			tab gwf_personal if e(sample)==1
			swilk log_chinafdi if e(sample)==1
			qui:xtregar cub_primaryfdigdp gwf_personal log_chinafdi $cvarlist if log_chinafdi~=., re 
			est store china2`i'	
		}
 		gen hi =.
		gen lo =.
		gen mhi  =.
		gen mlo =.
		gen b =.
		gen se =.
		gen count =_n
		gen model = ""
		gen variable = ""			

 		global imp ="china1"
		global count=10									/* number of specifications to test */
		global ac = $count
		global imp ="china1"
		local var = "gwf_pers allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi"
		foreach cvar of local var {
			global v = "`cvar'"						/* name of variable of interest to plot */
			qui:replace variable = "$v" if count==$count
			jwmi 
		}
		gen e=round(b,.001)
		gen s=round(se,.001)
		browse variable e s hi lo
		twoway (scatter count b if count<=10,ylab(1(1)$ac,glcolor(gs16)) mlab(e) mlabpos(12) xlab(-.05(.05).15) ///
		mcolor(gs6) msymbol(plus) yscale(range(0.75 10.25))  xtitle(Coefficient estimate) xline(0,lpat(dash))) ///
		(rspike hi lo count if count<=10, horizontal ytitle("") title(Reduced sample,size(medium)) ///
		ylab(1 `""Total" "Developing FDI""' 2 `""Oil reserves" "per cap. (log)""' 3 "Civil conflict"  ///
		4 `""Annual" "GDP growth""' 5 "Trade (log)" 6 "Population (log)" 7 `""GDP" "per cap. (log)""' ///
		8 `""Regime" "Duration""' 9 "Expropriations" 10 "{bf:Personalist}",labsize(small))  lcolor(gs6) lwidth(medthin) ///
		legend(off) scheme(lean2)) (rspike mhi mlo count if count<=10, lwidth(thick) lcolor(gs6) horizontal saving(h1.gph,replace))
		drop s e
		
 		global imp ="china2"		
		global count=11									/* number of specifications to test */
		global ac = $count
		local var = "gwf_pers log_china allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi "
		foreach cvar of local var {
			global v = "`cvar'"						/* name of variable of interest to plot */
			qui:replace variable = "$v" if count==$count
			jwmi 
		}
		gen e=round(b,.001)
		gen s=round(se,.001)
		browse variable e s hi lo
		twoway (scatter count b if count<=11,ylab(1(1)$ac,glcolor(gs16)) mlab(e) mlabpos(12) xlab(-.05(.05).15) ///
		mcolor(gs6) msymbol(plus) yscale(range(0.75 11.25))  xtitle(Coefficient estimate) xline(0,lpat(dash))) ///
		(rspike hi lo count if count<=11, horizontal ytitle("") title(Add Chinese FDI,size(medium)) ///
		ylab(1 `""Total" "Developing FDI""' 2 `""Oil reserves" "per cap. (log)""' 3 "Civil conflict"  ///
		4 `""Annual" "GDP growth""' 5 "Trade (log)" 6 "Population (log)" 7 `""GDP" "per cap. (log)""' ///
		8 `""Regime" "Duration""' 9 "Expropriations" 10 "Chinese FDI" 11 "{bf:Personalist}",labsize(small))  lcolor(gs6) lwidth(medthin) ///
		legend(off) scheme(lean2)) (rspike mhi mlo count if count<=11, lwidth(thick) lcolor(gs6) horizontal saving(h2.gph,replace))
		drop s e
		gr combine h1.gph h2.gph
		graph export "$dir\golden\China-FDI.pdf", as(pdf) replace	
		
		
***************************************
*** Appendix K: ONDD political risk ***
***************************************
		use temp,clear
		sort cow year
		merge cow year using "$dir\ONDD-1992-2013.dta"
		tab _merge
		tab country1 if _merge==2 & year<2011
		tsset cow year
		gen lONDD = l.ONDD_score
		gen priordem = gwf_prior_original=="democracy" | allregime==1
		* keep only the GWF autocracy and democracy data *
		drop if allregime==.
			
		global cvar = "gtime oilpc allexp lgdpcap lpop lopenness grow incidence"
		global unit = "i.year meast americas ssa asia easia"
		tsset cow year

		* Plot *
		egen regimemean  =mean(ONDD_score),by(allregime)
		egen tag = tag(allregime) if regimemean~=.
		label define reg 1 "Democracy" 2 "Military" 3 "Monarchy" 4  "Party"  5 "Personal"
		label values allregime reg  
		graph bar regimemean if tag==1,over(allregime) ytitle(Average ONDD score,height(6)) ///
			title(Regime type and political risk) scheme(lean2) ylab(,glcol(gs15)) saving(h1.gph,replace)  
		ttest ONDD_score if gwf_non=="NA",by(gwf_pers)
		ttest ONDD_score if allregime==1 | allregime==5,by(gwf_pers)
		ttest ONDD_score if allregime==2 | allregime==5,by(gwf_pers)
		ttest ONDD_score if allregime==3 | allregime==5,by(gwf_pers)
		ttest ONDD_score if allregime==4 | allregime==5,by(gwf_pers)
		replace grow  = grow/10
		
		* Post-2001 
		egen regimemean2002  =mean(ONDD_score) if year>=2002,by(allregime)
		egen tag2002 = tag(allregime) if regimemean~=. & year>=2002
		graph bar regimemean if tag==1,over(allregime) ytitle(Average ONDD score,height(6)) ///
			title("Regime type and political risk, 2002-2010") scheme(lean2) ylab(,glcol(gs15)) 
		
		******************
		*** Figure K-1 ***
		******************
		* Reported *
		ologit ONDD_score $unit $cvar gwf_party gwf_military gwf_monarchy gwf_pers,vce(cluster cow)
		 egen count=count(year) if e(sample)==1,by(gwf_casename)
		 tab count
		est store ondd1
			label var lgdpcap  "GDP per cap. (log)"
			label var lgdp  "GDP (log)"
			label var lpop  "Population (log)"
			label var lopenness  "Trade open (log)"
			label var grow "Annual GDP Growth"
			label var allexp "Expropriations"
			label var incidencev413 "Civil conflict"
			label var gwf_personal "Personalist"
			label var gwf_party "Party"
			label var gwf_military "Military"
			label var gwf_monarchy "Monarchy"
			label var gtime "Regime duration (log)"
			label var oilpc "Oil per cap. (log)"
		coefplot (ondd1, msymbol(D)),scheme(lean2) title("Political Risk") ///
			drop(_cons meast americas ssa asia easia 19* 20*) ///
			order(gwf_personal gwf_party gwf_military gwf_monarchy lgdp lgdpcap lpop lopenness) ///
			scale(.75) xlab(-2(.5)2) xline(0, lpattern(dash)) grid(glcolor(gs15)) mfcolor(white)  ///
			levels(95 90) xtitle("  Coefficient estimate", height(3)) saving(h2.gph,replace)  
			gr combine h1.gph h2.gph,xsize(8)
		graph export "$dir\golden\ONDD.pdf", as(pdf) replace	

		* Parsimonious *
		xtreg ONDD_score i.year gwf_pers,vce(cluster cow)
		xtologit ONDD_score i.year gwf_pers,vce(cluster cow)

		* Baseline *
		xtreg ONDD_score $unit $cvar gwf_party gwf_military gwf_monarchy gwf_pers,re vce(cluster cow)
		xtologit ONDD_score $unit $cvar gwf_party gwf_military gwf_monarchy gwf_pers,vce(cluster cow)

		* 2002-2010 only *
		xtreg ONDD_score $unit $cvar gwf_party gwf_military gwf_monarchy gwf_pers if year>=2002,re vce(cluster cow)
		xtologit ONDD_score $unit $cvar gwf_party gwf_military gwf_monarchy gwf_pers if year>=2002,vce(cluster cow)
		
		* Compare personalist to all others *
		xtreg ONDD_score $unit $cvar gwf_pers,re vce(cluster cow)
		xtologit ONDD_score $unit $cvar  gwf_pers,vce(cluster cow)

		* Just panels with more than 3 years *
		xtreg ONDD_score $unit $cvar gwf_party gwf_military gwf_monarchy gwf_pers if count>=4,re vce(cluster cow)
		xtologit ONDD_score $unit $cvar gwf_party gwf_military gwf_monarchy gwf_pers if count>=4,  vce(cluster cow)

		* AR(1) *
		xtregar ONDD_score meast americas ssa asia easia $cvar gwf_party gwf_military gwf_monarchy gwf_pers,rhotype(tscorr)
		xtgls ONDD_score meast americas ssa asia easia $cvar gwf_party gwf_military gwf_monarchy gwf_pers,corr(ar1) panel(het) force
		 
		* HAC *
		 ivreg2 ONDD_score meast americas ssa asia easia $cvar gwf_party gwf_military gwf_monarchy gwf_pers, rob bw(auto)
		 
	
	****************************
	*** Export concentration ***
	****************************
	cd "$dir"
	use temp,clear
	gen p_exp = logit(hhi_2digit_p_e)
	gen s_exp = logit(hhi_2digit_s_e)
	gen time = year-1979
	global x = "lgdpcap lpop lopen oilpc time"
	global region = "americas asia easia meast ssa"
	global regime = "gwf_personal"
	xtset cow year
	
		* Reported Primary sector model *
			*  RE w. ar1 errors *
			xtregar p_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & ///
			allregime~=. & year>=1980,re
			est stor exp1
		* Reported Secondary sector model *
			*  RE w. ar1 errors *
			xtregar s_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & ///
			allregime~=. & year>=1980,re
			est stor exp2
	
		*****************
		*** Figure 11 ***
		*****************
			* Plot estimates *
			label var lpop "Population"
			label var lgdpcap "GDP pc"
			label var lopen "Open"
			label var oilpc "Oil rents"
			label var gwf_personal "Personalist"
			coefplot (exp1, msymbol(D)) (exp2, msymbol(T)), title("Export concentration")/*
			*/ scheme(lean2) drop($region _cons time) /*
			*/ order(gwf_personal gwf_monarchy gwf_party gwf_military oilpc) /*
			*/ xlab(-.4 (.1) .3) xline(0, lpattern(dash)) grid(glcolor(gs15)) mfcolor(white) /*
			*/ ysize(3) xsize(2.5)   /*
			*/ legend(label(3 "Primary sector") label(6 "Secondary sector")   pos(6) ring(1.5) col(3))  /*
			*/ levels(95 90) xtitle("  Coefficient estimate", height(6))	
			graph export "$dir\golden\Export-concentration.pdf", as(pdf) replace
			graph export "$dir\golden\ISQ-Figure-11.png", as(png) replace
		
		*************************
		***** Primary sector ****
		*************************
		* Different specifications *
			* No controls *
			xtregar p_exp gwf_pers if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & ///
			allregime~=. & year>=1980,re
			
			* other regime types *
			xtregar p_exp gwf_pers gwf_party gwf_mil gwf_mon $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & ///
			allregime~=. & year>=1980,re
			
			*drop region effects *
			xi:xtregar p_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & ///
			allregime~=. & year>=1980,re
			
			* add other sector *
			xtregar p_exp s_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & ///
			allregime~=. & year>=1980,re

			
		* Fix up errors in different ways *
			* GLS with het & psar1 errors *
			xtgls p_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & ///
			allregime~=. & year>=1980,cor(psar1) panel(het) force
			
			* ar(1) with FE and logit-transformed DV *
			xtregar p_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) &  ///
			allregime~=. & year>=1980,fe
			
			* newey *
			forval i = 1/3 {
				qui:newey p_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) &  ///
				allregime~=. & year>=1980,lag(`i') force
				lincom gwf_pers
			}
			
		* Drop influential countries, one at a time *
			local country = "Venezuela Libya Iraq Nigeria Azerbaijan Yemen Guinea Burundi"
			foreach c of local country {
				qui:xtregar p_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) ///
				& allregime~=. & year>=1980 & gwf_country~="`c'",re
				lincom gwf_pers
			}

		*** Lag DV models ***	
			* Lag DV with cluster SE with GLM logit link *
			glm hhi_2digit_p_e l.hhi_2digit_p_e gwf_pers $region $x ///
			if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & allregime~=. & year>=1980, ///
			fam(bin) link(logit) vce(cluster cow)
			
			* Lag DV with logit-transformed DV & ar(1) & het errors *
			xtgls p_exp l.p_exp gwf_pers $region $x ///
			if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & allregime~=. & year>=1980, ///
			panel(het) cor(ar1) force

			* Lag DV with logit-transformed DV & psar(1) & het errors *
			xtgls p_exp l.p_exp gwf_pers  $region $x ///
			if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & allregime~=. & year>=1980, ///
			panel(het) cor(psar1) force
			
			* Lag DV with ar(1) & cluster-rob errors with GLM logit link | add region & year effects *
			xtgee hhi_2digit_p_e l.hhi_2digit_p_e i.year $region $region gwf_pers  $x ///
			if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & allregime~=. & year>=1980, ///
			cor(ar1) link(logit) fam(bin) vce(rob) force
			
			* Lag DV with RE and cluster-robust errors * 
			xtreg p_exp l.p_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) ///
			& allregime~=. & year>=1980,re vce(cluster cow)
			
			
		***************************
		***** Secondary sector ****
		***************************		
		* Different specifications *
			* No controls *
			xtregar s_exp gwf_pers if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & ///
			allregime~=. & year>=1980,re
			
			* other regime types *
			xtregar s_exp gwf_pers gwf_party gwf_mil gwf_mon $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & ///
			allregime~=. & year>=1980,re
			
			* drop region effects *
			xi:xtregar s_exp   gwf_pers $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & ///
			allregime~=. & year>=1980,re
			
			* add other sector *
			xtregar s_exp p_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & ///
			allregime~=. & year>=1980,re

			
		* Estimate errors in different ways *
			* GLS with het & psar1 errors *
			xtgls s_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & ///
			allregime~=. & year>=1980,cor(psar1) panel(het) force
			
			* ar(1) with FE and logit-transformed DV *
			xtregar s_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) &  ///
			allregime~=. & year>=1980,fe
			
			* newey *
			forval i = 1/3 {
				qui:newey s_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) &  ///
				allregime~=. & year>=1980,lag(`i') force
				lincom gwf_pers
			}
			
		* Drop influential countries, one at a time *
			local country = "Venezuela Libya Iraq Nigeria Azerbaijan Yemen Guinea Burundi"
			foreach c of local country {
				qui:xtregar s_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) ///
				& allregime~=. & year>=1980 & gwf_country~="`c'",re
				lincom gwf_pers
			}


		*** Lag DV models ***	
			* Lag DV with cluster SE with GLM logit link *
			glm hhi_2digit_s_e l.hhi_2digit_p_e gwf_pers $region $x ///
			if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & allregime~=. & year>=1980, ///
			fam(bin) link(logit) vce(cluster cow)
			
			* Lag DV with logit-transformed DV & ar(1) & het errors *
			xtgls s_exp l.s_exp gwf_pers $region $x ///
			if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & allregime~=. & year>=1980, ///
			panel(het) cor(ar1) force

			* Lag DV with logit-transformed DV & psar(1) & het errors *
			xtgls s_exp l.s_exp gwf_pers  $region $x ///
			if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & allregime~=. & year>=1980, ///
			panel(het) cor(psar1) force
			
			* Lag DV with ar(1) & cluster-rob errors with GLM logit link | add region & year effects *
			xtgee hhi_2digit_s_e l.hhi_2digit_s_e i.year  gwf_pers  $x ///
			if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) & allregime~=. & year>=1980, ///
			cor(ar1) link(logit) fam(bin) vce(rob) force
			
			* Lag DV with RE and cluster-robust errors * 
			xtreg s_exp l.s_exp gwf_pers $region $x if (oecd2==0 | (cow==70 | cow==155 | cow==640 | cow==732)) ///
			& allregime~=. & year>=1980,re vce(cluster cow)	

 
		*************************************	
		*** Table M-1: US Fixed Asset FDI ***
		*************************************
			cd "$dir"
			use temp.dta, clear
			joinby cowcode year using "$dir\us-fixed-asset-fdi\fixedcapexp2000.dta" ,unmatched(both)
			tab _merge
			drop if _merge==2
			drop _merge

			gen capexpgdp=capex2000*1000000/cgdp
			gen cub_capexgdp=(capexpgdp)^(1/3)

			global cvarlist="allexp gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
			lab var gwf_personal "Personalist"
			lab var allexp "Expropriations"
			lab var gtime "Regime duration"
			lab var lgdpcap "GDP per cap. (log)"
			lab var lpop "Population (log)"
			lab var lopenness "Trade (log)"
			lab var grow "Annual GDP Growth"
			lab var incidencev413 "Civil Conflict"
			lab var meanres "Oil reserves per cap. (log)"
			lab var ldevelopingfdi "Total Developling FDI"
			lab var asia "Asia"
			lab var america "Americas"
			lab var easia "East Asia"
			lab var ssa "Sub-Saharan Africa"
			 
			macro define output "label se dec(3) adec(3) addstat(R-squared,e(r2_o)) "
			xtset cowcode year
			eststo usfdi1: xtregar cub_capexgdp gwf_personal $cvarlist, re 
			eststo usfdi2: xtregar cub_capexgdp gwf_personal $cvarlist if cub_capexgdp<.47, re 

			outreg2 [usfdi1 usfdi2] using "Table_usfdi.xls", $output replace
			drop if year<1997
			keep country year cowcode cub_capexgdp gwf_personal $cvarlist oilpc allfdi
			save  "$dir\us-fixed-asset-fdi\us-capex-imputation.dta",replace
	 
			** retrieve regression results from the 10 imputed data sets
			clear
			cd "$dir\us-fixed-asset-fdi"
			**** 
			! dir us_capex*.csv /a-d /b > filelist1.txt

			* command started with "file"* execute lines 2364-2375 together
			file open myfile using "filelist1.txt", read
			file read myfile line
			local replace "replace" 
			while r(eof)==0 {
			 import delimited `line',clear
			 xtset cowcode year
			 xtregar cub_capexgdp gwf_personal allexp gtime lgdpcap lpop lopenness grow incidencev413 meanreserves ldevelopingfdi asia americas easia ssa, re
			 regsave gwf_personal allexp gtime lgdpcap lpop lopenness grow incidencev413 meanreserves ldevelopingfdi asia americas easia ssa _cons using us_capex_coefs.dta, ci level(95) `replace'
			 local replace "append"
			 file read myfile line
			}
			file close myfile

			/* see results_us_capex.csv, which is generated by the R code, for model reported in column 1 */
 
 		***********************************************************************************
		* Footnote about changing the value of the expropriation lag to 6 or 10 (from 8)  *
		***********************************************************************************
			forval i = 1(1)$m {
				import delimited using "$dir\imputed-fdi\primary`i'.csv",clear
				qui:sort cow year
				qui:merge cow  year using "$dir\temp.dta"
				tab _merge
				global cvarlist="allexp6 gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
				qui:tsset cow year
				xtserial cub_primaryfdigdp gwf_personal $cvarlist
				qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist, re 
				est store primaryallexp6`i'
				global cvarlist="allexp10 gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi asia america easia ssa"
				qui:tsset cow year
				xtserial cub_primaryfdigdp gwf_personal $cvarlist
				qui:xtregar cub_primaryfdigdp gwf_personal $cvarlist, re 
				est store primaryallexp10`i'
			}
			
				gen hi =.
				gen lo =.
				gen mhi  =.
				gen mlo =.
				gen b =.
				gen se = .
				gen count =_n
				gen model = ""
				gen variable = ""			
				global count=10									/* number of specifications to test */
				global ac = $count
				global imp ="primaryallexp6"
				local var = "gwf_pers allexp6 gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi"
				foreach cvar of local var {
						global v = "`cvar'"						/* name of variable of interest to plot */
						qui:replace variable = "$v" if count==$count
						jwmi 
				}
				gen e=round(b,.001)
				gen s=round(se,.001)
				browse variable e s hi lo
				
				twoway (scatter count b if count<=10,ylab(1(1)$ac,glcolor(gs16)) mlab(e) mlabpos(12) xlab(-.05(.05).1) ///
				mcolor(gs6) msymbol(plus) yscale(range(0.75 10.25))  xtitle(Coefficient estimate) xline(0,lpat(dash))) ///
				(rspike hi lo count if count<=10, horizontal ytitle("") title(Expropriation lagged 6 years,size(medium)) ///
				ylab(1 "Total Developing FDI" 2 "Oil reserves per cap. (log)" 3 "Civil conflict"  ///
				4 "Annual GDP Growth" 5 "Trade (log)" 6 "Population (log)" 7 "GDP per cap. (log)" ///
				8 "Regime duration" 9 "Expropriations" 10 "{bf:Personalist}")  lcolor(gs6) lwidth(medthin) ///
				legend(off) scheme(lean2)) (rspike mhi mlo count if count<=10, lwidth(thick) lcolor(gs6) horizontal saving(a.gph,replace))
 
				drop e s
				
				global imp ="primaryallexp10"
				local var = "gwf_pers allexp10 gtime lgdpcap lpop lopenness grow incidencev413 meanres ldevelopingfdi"
				foreach cvar of local var {
						global v = "`cvar'"						/* name of variable of interest to plot */
						qui:replace variable = "$v" if count==$count
						jwmi 
				}
				gen e=round(b,.001)
				gen s=round(se,.001)
				browse variable e s hi lo
				twoway (scatter count b if count<=10,ylab(1(1)$ac,glcolor(gs16)) mlab(e) mlabpos(12) xlab(-.05(.05).1) ///
				mcolor(gs6) msymbol(plus) yscale(range(0.75 10.25))  xtitle(Coefficient estimate) xline(0,lpat(dash))) ///
				(rspike hi lo count if count<=10, horizontal ytitle("") title(PExpropriation lagged 10 years,size(medium)) ///
				ylab(1 "Total Developing FDI" 2 "Oil reserves per cap. (log)" 3 "Civil conflict"  ///
				4 "Annual GDP Growth" 5 "Trade (log)" 6 "Population (log)" 7 "GDP per cap. (log)" ///
				8 "Regime duration" 9 "Expropriations" 10 "{bf:Personalist}")  lcolor(gs6) lwidth(medthin) ///
				legend(off) scheme(lean2)) (rspike mhi mlo count if count<=10, lwidth(thick) lcolor(gs6) horizontal saving(b.gph,replace))
 
				gr combine a.gph b.gph
				graph export "$dir\golden\Exprop-Lags.pdf", as(pdf) replace
				erase a.gph
				erase b.gph
				
				************************
				*** Figures 9 and 10 ***
				************************
				cd "$dir\corruption"
				do rgi
				do corruption
				

 				
				*** ERASE temporary files and .gph ***
				cd "$dir"
				erase temp_primary.dta
				erase temp_secondary.dta
				forval i =1(1)4{
					erase f`i'.gph
				}
				forval i =1(1)10{
					erase h`i'.gph
				}
				forval i =1(1)2{
					erase s`i'.gph
				}
						
				****************
				*** Figure 8 ***
				****************
				cd "$dir\industry-level"
				do savecoefs-industry   /* estimates saved in coefs.dta and coefs_nonimputed.dta */
				
				
			****************** The END ********************	
log close
	 
	 
	
	
	
	
